# Moving player in Box2d without forces

How do I move player with keyboard without applying forces? If I do playerBody.setLinearVelocity(new B2Vec2(0, 2)) it moves the player but when I release the key for movement, the ball is continuously moving for few seconds.

Applying a force still the way to do it. But instead, you can apply directly the impulse for the desired speed. You can still make the player instantly stop (instead of decelerating) You just need to set the desired speed to zero. Here's the snippet:

b2Vec2 vel = body->GetLinearVelocity();
float desiredVel = 0;
switch ( moveState )
{
case MS_LEFT:  desiredVel = -5; break;
case MS_STOP:  desiredVel =  0; break;
case MS_RIGHT: desiredVel =  5; break;
}
float velChange = desiredVel - vel.x;
float impulse = body->GetMass() * velChange; //disregard time factor
body->ApplyLinearImpulse( b2Vec2(impulse,0), body->GetWorldCenter() );


If you want gradual acceleration, change the switch block by:

  case MS_LEFT:  desiredVel = b2Max( vel.x - 0.1f, -5.0f ); break;
case MS_STOP:  desiredVel = 0; break;
case MS_RIGHT: desiredVel = b2Min( vel.x + 0.1f,  5.0f ); break;


You should be fine with this.

• Note: this is in C++, but should be easy to understand and use in AS3. – Gustavo Maciel Jan 13 '13 at 2:07

Depending on what you want to do, you can use

playerBody.setPosition(new b2Vec(x,y))


so while you have your key pressed down you can keep increasing your position by 1 or something.

or when the key is down you can apply the linear velocity and when the key is up you can set the linear velocity and to 0.

The velocity will always be moving the body until the forces in the world acting against the reduce the velocity to 0;

• What happens when the new position is inside a collidable object ? – rootlocus Jan 13 '13 at 8:47
• @rootlocus it'll pop out. – Marc Jan 14 '13 at 1:43