Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a body has almost stopped moving in libgdx + box2d

So, I have a player body + fixture etc, it is essentially a ball that bounces around.

I want to detect when it is 'pretty much' finished moving.

At the moment I do this:

public Boolean isStopped() {
    return body.getLinearVelocity().x <= 0.3f && body.getLinearVelocity().y <= 0.3f;
}

This mostly works, the problem being when the player hits something, there's a split second where its velocity is 0, so this returns true. What I really wanted is to just return true when it is basically finished. Preferably within a range that I can set to whatever I like as I tweak the physics of my game world.

I can't use a check on whether it is sleeping or not as that comes too late, it doesn't sleep until after it has stopped having forces act upon it, I need just before.

I could just store how long it has been stopped/a count of stopped steps, but I was hoping there would be a nice pre existing method that I missed.

Any ideas?

like image 349
Tom Manterfield Avatar asked Feb 24 '14 21:02

Tom Manterfield


Video Answer


1 Answers

You can keep track of recent movement and update it by mixing in a little of the current speed each time step:

float speedNow = body.getLinearVelocity().len();
recentSpeed = 0.1 * speedNow + 0.9 * recentSpeed;
if ( recentSpeed < someThreshold )
    ... do something ...

You would need to set recentSpeed to a suitably high value to begin with, otherwise it might be below the threshold in the first time step.

like image 63
iforce2d Avatar answered Sep 20 '22 23:09

iforce2d