I want to have a body move at a constant velocity, but react to collisions.

My example game is a train, I want it to move at 1 meter a second. If an obstacle appears on the tracks, I want it to react by smashing through it (which will normally slow it down). But when the obstacle is cleared, I want the train to accelerate back to 1 m/s and continue on.

It seems like the applyLinearImpulse() and applyLinearForce() methods are the place to start, but those are one-shot methods.



If you apply a linear impulse to your train body every frame your train will speed up. You can then check if the velocity of the train exceeds the maximum velocity and scale down the speed.

body.applyLinearImpulse((body.getLinearVelocity()), body.getPosition(), true);

// limit max speed
Vector2 vel = body.getLinearVelocity();
float speed = vel.len();
if ( speed > MAX_SPEED ) {
    body.setLinearVelocity( vel.scl(MAX_SPEED / speed));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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