Body OnUpdate callback ?

Topics: Developer Forum
Jun 13, 2012 at 6:14 PM
Edited Jun 13, 2012 at 6:16 PM

Is there a OnUpdate() event fired somewhere when a body's position/rotation is updated ?

I'm building a component based game where generic objects aggregate components. Each component has a unique role and define the object. For instance, I have a SpriteComponent responsible for drawing the object on the screen. I have an other one called ControlComponent which detects user input and changes the position of the sprite on the screen. 

So I want to create a FarseerComponent which adds the physics to the object, giving it a body. The problem is, the SpriteComponent does not know about the FarseerComponent. So I thought about having a callback function called every time the body's position is updated, and this very function would update the Sprite's position.


Any insights ?


I like oranges.

Jun 13, 2012 at 6:53 PM
Edited Jun 13, 2012 at 7:08 PM

I think what you want is something like the MotionState in Bullet Physics which is the main way to deal with physics updates in that engine. It looks like a good idea given its wide usage.

This doesn't exist in Box2D and consequently in Farseer. It will however be extremenly easy to implement:

Have a class called MotionState attached to each fixture upon creation in the UserData field. The class keeps velocities (angular and linear and the body transform). After calling World.Step() in something like a PhysicsManager singleton that knows about the simulation, iterate over all bodies (World.BodyList), grab the MotionState of each fixture and call it's Update() method with the new data. The MotionState will be responsible for firing an OnUpdate() Event to which other entities can subscribe. Other useful events could be OnPre/PostStep() (cancelling updates?), OnFixtureChanged, OnMotionStateChanged() and whatever else. Also the MotionState can  be extended through inheritance like in Bullet for more specific needs. I haven't actually looked at Bullet's implementation but should be in that spirit.

Note that this changes the chain of responsibility. I prefer a setup where the user code *pulls* data from the physics whenever needed. The above approach will mean that the PhysicsManager will *push* the physics onto the user code. Does this really play well with the way graphics engines work? In XNA Update() and Draw() are not synchronous for example (one can be faster than the other)...

Jun 13, 2012 at 8:22 PM

Thank you for your answer jerry.

I like the solution, however I found a much simpler solution to my problem. It was rather easy, although I'm not sure how much it impacts on the performances.

Every loop, in the Update() function of the FarseerComponent, I simply fetch the body's position and assign it to the Sprite's position.