Move body to a specific position - Box2D

Anubhav Sharma picture Anubhav Sharma · May 29, 2011 · Viewed 46.4k times · Source

I have a b2Body which I would like to move at a certain target position. I don't want to use the SetPosition function. How can I achieve this using :

  1. Changing linear velocities.
  2. Using mouseJoint. (The target position is fixed. Mouse is NOT involved.)

I'm using Box2DAS3 2.1a. Help in any other language would also be appreciated.

Answer

Tom Guinther picture Tom Guinther · Dec 20, 2011

The simplest way is actually to use SetPosition/SetTransform(position,angle). For example:

body->SetTransform(b2Vec2(0,0),body->GetAngle())

Obviously, the instantaneous jump means you are subverting the physics simulation but it is the simplest most direct way to set the position of a body.

Given that you don't want to use SetPosition (which is equivalent to the code posted above) then ApplyLinearImpulse with the appropriate force (based on the Mass and current speed of the body) will do the trick, and is more correct from a simulation point-of-view, but likely to be more problematic given potential side-effects, etc.

Anyway, iforce2d covered SetLinearVelocity..., and I would add that a mouse joint is very useful even when the "mouse" is not involved.