首页 > 解决方案 > How to move apply force to bodies in a top down game?

问题描述

So I am making a top down game where the player moves using WASD keys. For this I use

if (Gdx.input.isKeyPressed(Input.Keys.S) && b2dBody.getLinearVelocity().y >= -0.8) {
    b2dBody.applyLinearImpulse(new Vector2(0, -PLAYER_SPEED), b2dBody.getWorldCenter(), true);
} else if (Gdx.input.isKeyPressed(Input.Keys.W) && b2dBody.getLinearVelocity().y <= 0.8) {
    b2dBody.applyLinearImpulse(new Vector2(0f, PLAYER_SPEED), b2dBody.getWorldCenter(), true);
} else if (Gdx.input.isKeyPressed(Input.Keys.A) && b2dBody.getLinearVelocity().x >= -0.8) {
    b2dBody.applyLinearImpulse(new Vector2(-PLAYER_SPEED, 0), b2dBody.getWorldCenter(), true);
} else if (Gdx.input.isKeyPressed(Input.Keys.D) && b2dBody.getLinearVelocity().x <= 0.8) {
    b2dBody.applyLinearImpulse(new Vector2(PLAYER_SPEED, 0), b2dBody.getWorldCenter(), true);
}

But because the gravity is set to 0 world = new World(new Vector2(0, 0), true); the body doesn't stop. I was wondering if there was a way to keep the gravity the same while making the body stop after after a while? Thanks in advance.

标签: javalibgdxbox2d

解决方案


创建 box2d 主体时,您可以设置用于创建主体的BodyDeflinearDamping对象的值。 这个值总是会在物体移动时减慢物体的速度(例如,当应用线性脉冲时)。

你可以像这样使用它:

BodyDef bodyDef = new BodyDef();
//set other body values
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(42f, 42f);
bodyDef.angle = 0f;
//...
bodyDef.linearDamping = 10f; // this will make the body slow down when moving

//create the body
Body body = world.createBody(bodyDef);

// TODO move the body arround and it will automatically slow down

推荐阅读