Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move body to a specific position - Box2D

Tags:

box2d

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.

like image 931
Anubhav Sharma Avatar asked May 29 '11 20:05

Anubhav Sharma


1 Answers

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.

like image 156
Tom Guinther Avatar answered Sep 30 '22 01:09

Tom Guinther