Page 1 of 1

Physics engine: how do you simulate top speed?

Posted: Sat Mar 18, 2023 4:52 am
by togFox
I have a physics body that I move around using impulses on the x and y axis. Positive X impulse moves the body to the right and negative X impulse moves the body to the left. With mass applied, I can get a nice seamless acceleration effect thanks to the hard work the Box2D does for me.

If I make up some numbers for example, if my body applies +1000 x impulse per second it will move to the right side of the screen in an ever increasing speed. I need it to reach a fabricated top speed and thought I'd ask if there is a 'best' way to do this in harmony with the engine?

The obvious one to me, for each dt, apply the (+1000 * dt) impulse then immediately do a body:getVelocity(). If the velocity is over the top speed then reduce that top speed with body:setVelocity(). I suspect that is a poor approach due to the setVelocity overriding the engine's natural way of applying physics.

What method have you used in the past that works well with the engine?

Re: Physics engine: how do you simulate top speed?

Posted: Sat Mar 18, 2023 9:36 pm
by pgimeno
One way to do this is to implement a kind of drag. Apply a force proportional to the velocity, and in the inverse direction to that of velocity, and the object will have a terminal velocity.

Re: Physics engine: how do you simulate top speed?

Posted: Sun Mar 19, 2023 7:05 am
by ivan
What method have you used in the past that works well with the engine?
Impulses are instant changes in velocity. If you want to change the velocity over time we use forces.
I need it to reach a fabricated top speed and thought I'd ask if there is a 'best' way to do this in harmony with the engine?
There is no such thing as "top speed" in Newtonian physics.

Having said that, Box2d already has a "maximum velocity" constraint. From what I can remember it varies depending to the time step.

You could use something like "linear damping" to simulate something like terminal velocity for falling bodies although it is not the same thing. There is no air resistance or rolling resistance in Box2d.

Re: Physics engine: how do you simulate top speed?

Posted: Sun Mar 19, 2023 9:59 am
by darkfrei
Just add the negative force in the amount and direction back to the velocity.
So,

Code: Select all

frictionForce = -c*v^2
And apply this force as other forces in your physics system.

Here minus means back to velocity direction:

Code: Select all

frictionForceX = -c*vx^2*math.sign(vx)
frictionForceY = -c*vy^2*math.sign(vy)
The c is a proportion factor, first set to 1 and change it higher if the friction was not enough.

Re: Physics engine: how do you simulate top speed?

Posted: Mon Mar 20, 2023 7:53 am
by togFox
As always - the best answer is simpler than you think. Thanks!