【问题标题】:How to give a player velocity from only one key press at a time LibGDX Box2dLibGDX Box2d 如何一次只按下一个键就为玩家提供速度
【发布时间】: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)
  • 是的,这是我的第一个想法,但我不知道如何检测多个键被按下。
  • 好吧,我从未使用过libgdxbox2d,但我想你可以输入if ((Gdx.input.isKeyPressed(Input.Keys.LEFT) || Gdx.input.isKeyPressed(Input.Keys.RIGHT)) &amp;&amp; (Gdx.input.isKeyPressed(Input.Keys.UP) || Gdx.input.isKeyPressed(Input.Keys.LEFT))) { 之类的东西来检测玩家是否按45 度角前进两个键。
  • 一个提示,将在未来为您解决问题。永远不要像你一样创建一个新的向量。这将导致在您的渲染周期中创建新对象,并在您失去对它们的引用时将其丢弃。您的内存使用量逐渐增加,最终垃圾收集将清除您丢弃的对象(在这种情况下是您的 Vector2)。垃圾收集成本很高,并且会导致帧速率抖动 - 尤其明显。

标签: java libgdx box2d


【解决方案1】:

如果需要,我认为您应该在归一化之前计算您的组合运动矢量并作为脉冲应用。你可以使用这样的东西:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    相关资源
    最近更新 更多