1
\$\begingroup\$

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.

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ Note: this is in C++, but should be easy to understand and use in AS3. \$\endgroup\$ Commented Jan 13, 2013 at 2:07
0
\$\begingroup\$

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;

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .