How to check that the body almost stopped moving in libgdx + box2d

So, I have a game body + device, etc., it is, in fact, a ball that bounces around.

I want to determine when it is "pretty much" completed.

I am currently doing this:

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

It basically works, the problem is when a player stumbles something, there is a second where his speed is 0, so this returns true. I really wanted to just return true when it is basically finished. Preferably, within the range that I can set on everything that I like when I customize the physics of my game world.

I can’t use the check whether he is sleeping or not, because it is too late, he does not sleep until he ceases to influence him, I need to do something earlier.

I could just store how long it was stopped / the number of steps stopped, but I was hoping there would be a good previous method that I skipped.

Any ideas?

+4
source share
3 answers

You can follow the last movement and update it, moving slightly at the current speed each time:

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

You will need to set it recentSpeedto a suitable value to begin with, otherwise it may be below the threshold in the first step.

+4
source

, , , ContactListener beginContact, ? isStopped. , , , , : ignore. , - : . , , .

ContactListener:

public void beginContact(Contact contact) {
    Body a = contact.getFixtureA().getBody();
    Body b = contact.getFixtureB().getBody();

    if (a == mBall) {
        a.setUserData(a.getLinearVelocity().len());
    } else if (b == mBall) {
        b.setUserData(b.getLinearVelocity().len());
    }
}

isStopped:

public Boolean isStopped() {
    float storedSpd = (Float) body.getUserData();
    float currentSpd = body.getLinearVelocity().len();

    if ((storedSpd > Float.MIN_VALUE) && (currentSpd > storedSpd)) {
        body.setUserData(Float.MIN_VALUE);
        return false;
    } else {
        return (currentSpd < THRESHOLD);
    }
}

, . , Float.MIN_VALUE.

+1

isStopped().

public Boolean isStopped(float delta) {
    boolean isMoving = (
            Math.abs(body.getLinearVelocity().x) >= 0.25f || Math.abs(body.getLinearVelocity().y) >= 0.25f);
    if(isMoving) {
        timeStopped = 0f;
        return false;
    } else {
        timeStopped += delta;
        return timeStopped >= 0.3f;
    }
}

timeStopped - , . true ( , ), . , , .

, , , box2d -, , , .

0

All Articles