Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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.

Source: http://www.iforce2d.net/b2dtut/constant-speed

share|improve this answer
    
Note: this is in C++, but should be easy to understand and use in AS3. –  Gustavo Maciel Jan 13 '13 at 2:07
add comment

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;

share|improve this answer
1  
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.