如何在自上而下的游戏中移动对body施加力?



所以我正在制作一款自上而下的游戏,其中玩家使用WASD键移动。我使用

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);
}

但是因为重力被设置为0world = new World(new Vector2(0, 0), true);,所以物体不会停止。我想知道是否有一种方法可以保持重力不变,同时使身体在一段时间后停止?提前谢谢。

当你创建一个box2d主体时,你可以设置BodyDef对象的linearDamping值,用于创建主体。
当物体移动时,这个值总是会减慢物体的速度(例如,当施加线性脉冲时)。

你可以这样使用:

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

最新更新