移动 Box2D Body 的简单方法

Simple way to move Box2D Body

在简单的 java 中,您可以像这样向坐标添加值:

object.x += 5;
object.y += 5;
render(object, object.x, object.y);

有什么方法可以对 Box2D 实体执行此操作吗?因为如果我这样做:

if(Gdx.input.isKeyPressed(Input.Keys.A) && player.getBody().getLinearVelocity().x >= -2.0f) {
            player.getBody().applyLinearImpulse(new Vector2(-0.12f, 0.0f), player.getBody().getWorldCenter(), true);
        }

然后物体继续朝那个方向移动,直到我施加不同的力。那么有没有办法让它移动一个恒定的量,而不是永远以恒定的速度移动它呢?我试过尝试摩擦,但似乎很痛苦。

Body 有一个 setTransform(float x, float y, float angle) 方法。

所以,player.getBody().setTransform(-0.12f, 0.0f, angle-here);

Peter 的代码也有效,但我找到了另一种方法,因为 setTransform 可能会导致潜在的意外失败:

    float velX = 0, velY = 0;
    if(Gdx.input.isKeyPressed(Input.Keys.W)) {
        velY = 2.0f ;
    } else if(Gdx.input.isKeyPressed(Input.Keys.D)) {
        velX = 2.0f;
    } else if(Gdx.input.isKeyPressed(Input.Keys.S)) {
        velY = -2.0f;
    } else if(Gdx.input.isKeyPressed(Input.Keys.A)) {
         velX = -2.0f;
    }

    player.getBody().setLinearVelocity(velX, velY);

每当按下一个键时,velXvelY 被设置,如果没有按下任何东西,它们默认设置为 0。