我有一个玩家通过按下箭头键来移动,这给了他速度。一切正常,唯一的问题是当按下多个箭头键时,玩家的速度会比正常情况下快。我认为这是因为这两个箭头键同时增加了玩家的速度。我的问题是如何防止这种情况发生,这意味着当按下多个箭头键时,玩家会获得通常的速度。感谢任何帮助代码如下。
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);
最佳答案
我认为你应该在标准化之前计算你的组合运动 vector ,如果需要的话,可以将其作为脉冲应用。你可以使用这样的东西:
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
关于java - 如何通过一次仅按一个按键来赋予玩家速度 LibGDX Box2d,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62162050/