简体   繁体   中英

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

I have a player the moves through the pressing of arrow keys which give him velocity. Everything works fine, the only problem is that the player goes faster than normal when more than one arrow key is pressed. I assume this is because both these arrow keys are increasing the player's velocity at the same time. My question is how would I prevent this from happening, meaning that when more than one arrow key is pressed the player gains the usual amount of velocity. Any help is appreciated Code is below.

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

I think you should calculate your combined movement vector before normalising and applying as an impulse if you need to. You can use something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM