0
\$\begingroup\$

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.

Thanks

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

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.getLinearVelocity(); 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)); } 
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.