Are all events one step late by design? #866
-
Hello, #include <box2d/box2d.h>
#include <iostream>
using namespace std;
int main()
{
b2WorldDef world_def = b2DefaultWorldDef();
auto world_id = b2CreateWorld(&world_def);
// Wall from x = 1 to x = 2
b2BodyDef body_def = b2DefaultBodyDef();
body_def.type = b2_staticBody;
body_def.position.x = 1.5f;
body_def.position.y = 11.0f;
auto wall_id = b2CreateBody(world_id, &body_def);
b2Polygon box = b2MakeBox(0.5f, 10.0f);
b2ShapeDef shape_def = b2DefaultShapeDef();
b2CreatePolygonShape(wall_id, &shape_def, &box);
// Bullet fired towards the wall
body_def = b2DefaultBodyDef();
body_def.type = b2_dynamicBody;
body_def.isBullet = true;
body_def.gravityScale = 0.0f;
body_def.position = b2Vec2{3.2f, 4.0};
body_def.linearVelocity = b2Vec2{-20.0f, 0.0f};
auto bullet_id = b2CreateBody(world_id, &body_def);
shape_def = b2DefaultShapeDef();
shape_def.isSensor = true;
b2Circle circle = { { 0.0f, 0.0f }, 0.1f };
b2CreateCircleShape( bullet_id, &shape_def, &circle);
while(true)
{
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
std::cout << "Step" << std::endl;
b2World_Step(world_id, timeStep, subStepCount);
auto bullet_pos = b2Body_GetPosition(bullet_id);
std::cout << "Bullet pos: " << bullet_pos.x << " " << bullet_pos.y << std::endl;
auto events = b2World_GetSensorEvents(world_id);
if(events.beginCount > 0)
{
std::cout << "Sensor begin" << std::endl;
break;
}
}
}
Outputs
I would expect the sensor begin event to be triggered when the bullet reaches x=1.86667, placing it inside the wall (which ranges from x=1 to x=2). However, it takes one more step to trigger the sensor event. Why is that? And is there any clean solution to get the event one frame earlier? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Contacts are computed at the beginning of the time step so that objects don't sink into each other. I've changed the behavior in main so that sensors are updated at the end of the time step. So there is no longer a delay for sensor events. |
Beta Was this translation helpful? Give feedback.
Contacts are computed at the beginning of the time step so that objects don't sink into each other.
I've changed the behavior in main so that sensors are updated at the end of the time step. So there is no longer a delay for sensor events.