如何通过一次LibGDX Box2d一次按键来赋予玩家速度

问题描述 投票:0回答:1

我有一个玩家通过按箭头键来移动,这使他具有速度。一切正常,唯一的问题是,当按下多个箭头键时,播放器的运行速度会比正常情况快。我认为这是因为这两个箭头键都在同时提高玩家的速度。我的问题是如何防止这种情况的发生,这意味着当按下多个箭头键时,玩家将获得通常的速度。感谢您的帮助,代码如下。

    if(Gdx.input.isKeyPressed(Input.Keys.LEFT) && player.b2Body.getLinearVelocity().x >= -2) {
        player.b2Body.applyLinearImpulse(new Vector2(-0.1f, 0), player.b2Body.getWorldCenter(), true);
    }
    else if(Gdx.input.isKeyPressed(Input.Keys.RIGHT) && player.b2Body.getLinearVelocity().x <= 2) {
        player.b2Body.applyLinearImpulse(new Vector2(0.1f, 0), player.b2Body.getWorldCenter(), true);
    }
    else if(Gdx.input.isKeyPressed(Input.Keys.LEFT) == Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
        player.b2Body.setLinearVelocity(0, 0);
    }
    if(Gdx.input.isKeyPressed(Input.Keys.UP) && player.b2Body.getLinearVelocity().y <= 2)
        player.b2Body.applyLinearImpulse(new Vector2(0, 2f), player.b2Body.getWorldCenter(), true);
    if(Gdx.input.isKeyPressed(Input.Keys.DOWN) && player.b2Body.getLinearVelocity().y >= -2)
        player.b2Body.applyLinearImpulse(new Vector2(0, -2f), player.b2Body.getWorldCenter(), true);
java libgdx box2d
1个回答
0
投票

我认为您应该在归一化并根据需要应用为冲量之前计算组合的运动矢量。您可以使用类似这样的内容:

var x = 0f
var y = 0f
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
    x -= -1
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
    x += 1
}
if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
    y += 2
}
if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
    y -= 2
}
val movementVector = Vector2(x,y)
// Now you have your combined movement vector that you should normalise and you can apply as a single impulse
© www.soinside.com 2019 - 2024. All rights reserved.