简体   繁体   中英

LibGDX: move and then stop box2d immediately

I'm working on a project in LibGDX. It's a 2d platform game. you can say it's like Super Mario.

So this is how i move my player to the right:

if (Gdx.input.isKeyPressed(Input.Keys.RIGHT))
    player.b2body.applyLinearImpulse(new Vector2(0.1f, 0), player.b2body.getWorldCenter(), true);
}

When i leave the key, the player is still moving a bit. (it's still have "Linear Impulse" force on his physical body i think).

How can i make it stop?

My question could be simple as: What is the best way to move a physical body on LibGDX in one direction while holding a key. and when i leave the key, the player stops immediately.

bdw - I have tryied with "setTransform" and it's making issues when the body is touching other objects - plus the sahpe come "before" the rest of the game in the screen (you can see it on debug)

Thanks.

Your method is OK. I would also recommend to set the max speed of your body:

if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) && player.b2body.getLinearVelocity().x < maxSpeed)
    player.b2body.applyLinearImpulse(new Vector2(0.1f, 0), player.b2body.getWorldCenter(), true);
}

Stop your body immediately by using the setLinearVelocity method.:

player.b2body.setLinearVelocity(0f, 0f);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM