簡體   English   中英

如何一次只按一個鍵為玩家提供速度 LibGDX Box2d

[英]How to give a player velocity from only one key press at a time LibGDX Box2d

我有一個玩家通過按下箭頭鍵來移動,這給了他速度。 一切正常,唯一的問題是當按下多個箭頭鍵時播放器的速度比正常速度快。 我認為這是因為這兩個箭頭鍵同時增加了玩家的速度。 我的問題是如何防止這種情況發生,這意味着當按下多個箭頭鍵時,玩家會獲得通常的速度。 任何幫助表示贊賞代碼如下。

    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);

我認為你應該在歸一化之前計算你的組合運動矢量,如果需要的話作為脈沖應用。 你可以使用這樣的東西:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM