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

时间:2016-07-27 08:51:52

标签: java libgdx box2d

我正在制作一个游戏玩家,现在我正在制作玩家动作。所以当我按下A'时,玩家向左移动(player.moveLeft());当我按下' D'玩家移动到rigth(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&#39; A&#39;或者&#39; D&#39;在跳跃之前,当玩家跳跃并且我释放钥匙时,玩家继续前进。我该怎么解决?请帮帮我!!

1 个答案:

答案 0 :(得分:1)

你必须操纵X轴速度:

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

这样,Y轴速度保持不变,但你的玩家不会侧身移动。

相关问题