如何在 libGDX (Box2D) 中阻止 body 的冲量和力而不是重力?

How to stop a body's impulses and forces but not gravity in libGDX (Box2D)?

我正在制作平台游戏,现在我正在制作玩家动作。所以当我按下 'A' 时,播放器向左移动 (player.moveLeft());当我按下 'D' 时,播放器会移动到右边 (player.moveRigth());当我按下 'W' 时,播放器跳转 (player.jump()).

public void moveLeft() {
    if(Gdx.input.isKeyPressed(Keys.A) &&
      !Gdx.input.isKeyPressed(Keys.D) &&
      body.getLinearVelocity().x > -MAXIMUM_VELOCITY){
        left = true;
        body.applyLinearImpulse(-3, 0, body.getPosition().x, body.getPosition().y, true);
    }else if(Gdx.input.isKeyPressed(Keys.D) &&
             Gdx.input.isKeyPressed(Keys.A) &&
             !inTheAir){
        stop();
    }else if(!Gdx.input.isKeyPressed(Keys.A) && 
             !Gdx.input.isKeyPressed(Keys.D) &&
             !inTheAir){
        stop();
    }
}

public void moveRigth() {
    if(Gdx.input.isKeyPressed(Keys.D) &&
      !Gdx.input.isKeyPressed(Keys.A) &&
      body.getLinearVelocity().x < MAXIMUM_VELOCITY){
        rigth = true;
        body.applyLinearImpulse(3, 0, body.getPosition().x, body.getPosition().y, true);
    }else if(Gdx.input.isKeyPressed(Keys.D) &&
             Gdx.input.isKeyPressed(Keys.A) &&
             !inTheAir){
        stop();
    }else if(!Gdx.input.isKeyPressed(Keys.D) &&
            !Gdx.input.isKeyPressed(Keys.A) &&
            !inTheAir){
        stop();
    }
}

public void stop(){
    body.setLinearVelocity(0, 0);
    body.setAngularVelocity(0);
}

public void jump(){
    if(!inTheAir && Gdx.input.isKeyPressed(Keys.W)){
        inTheAir = true;
        body.setLinearVelocity(0, 0);
        body.setAngularVelocity(0);
        body.applyLinearImpulse(0, 7, body.getPosition().x, body.getPosition().y, true);
    }
}

它有效,但我有一个问题:当我在跳跃前按下 'A' 或 'D' 时,当玩家正在跳跃并且我松开按键时,玩家继续移动。我该如何解决?请帮帮我!!

您必须操纵 X 轴速度:

Vector2 vel = body.getLinearVelocity();
vel.x = 0f;
body.setLinearVelocity(vel);

这样,Y 轴速度保持不变,但您的播放器不会侧向移动。