【发布时间】:2020-06-02 22:00:49
【问题描述】:
我有一个玩家通过按下箭头键来移动,这给了他速度。一切正常,唯一的问题是当按下多个箭头键时播放器的速度比正常速度快。我认为这是因为这两个箭头键同时增加了玩家的速度。我的问题是如何防止这种情况发生,这意味着当按下多个箭头键时,玩家会获得通常的速度。任何帮助表示赞赏代码如下。
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);
【问题讨论】:
-
能否再添加一条
if语句来检测是否按下了多个键,如果是,则将速度除以Math.sqrt(2D)? -
是的,这是我的第一个想法,但我不知道如何检测多个键被按下。
-
一个提示,将在未来为您解决问题。永远不要像你一样创建一个新的向量。这将导致在您的渲染周期中创建新对象,并在您失去对它们的引用时将其丢弃。您的内存使用量逐渐增加,最终垃圾收集将清除您丢弃的对象(在这种情况下是您的 Vector2)。垃圾收集成本很高,并且会导致帧速率抖动 - 尤其明显。