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 :
- Changing linear velocities.
- 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.
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.
The simplest way would be to set the linear velocity of the body so that it will cover the necessary distance in one time step. eg. if the body needs to move (2,3) units to get to the desired location and your timestep is 60Hz you could SetLinearVelocity(120,180) for one time step. In the next time step you would of course have to set the velocity back to zero to stop it flying of into the distance. The result of this is not much different to if you had used SetTransform, except CCD will work and if anything is in the way it will get whacked.
If you don't want the body to arrive in one time step, just limit the max speed it can have.
If you would rather use ApplyForce/ApplyLinearImpulse, you could do something similar but you need to take into account the current speed of the body too. You might find this page helpful, it explains the rotation version of this but the principle is the same: http://www.iforce2d.net/b2dtut/rotate-to-angle
来源:https://stackoverflow.com/questions/6170087/move-body-to-a-specific-position-box2d