LordCanada LordCanada - 3 months ago 13
Java Question

libgdx some keypresses faster than others?

I started coding with libgdx recently and built a little "move around in a world" game. The problem is that it is faster going Up and Left (W and A) than going Right and Down. There is no difference in the code of W,A and of D,S.
Here's my code for the input handling that just gets called every frame after "render":

public void processInput() {
float delta = Gdx.graphics.getDeltaTime();
System.out.println(1.0/delta);
if (Gdx.input.isKeyJustPressed(Keys.A)) {
player.posX -= 100 * delta;
player.startAnimation(0); // Animation 0 = LEFT
elapsedTime = 0;
} else if (Gdx.input.isKeyJustPressed(Keys.D)) {
player.posX += 100 * delta;
player.startAnimation(1); // Animation 1 = RIGHT
elapsedTime = 0;
}
if (Gdx.input.isKeyJustPressed(Keys.W)) {
player.posY -= 100 * delta;
player.startAnimation(2); // Animation 2 = BACK
elapsedTime = 0;
} else if (Gdx.input.isKeyJustPressed(Keys.S)) {
player.posY += 100 * delta;
player.startAnimation(3); // Animation 3 = FRONT
elapsedTime = 0;
}
if(Gdx.input.isKeyJustPressed(Keys.ESCAPE)){
Gdx.app.exit();
}

boolean pressed = false;
if (Gdx.input.isKeyPressed(Keys.A)) {
player.posX -= 100 * delta;
pressed = true;
} else if (Gdx.input.isKeyPressed(Keys.D)) {
player.posX += 100 * delta;
pressed = true;
}
if (Gdx.input.isKeyPressed(Keys.W)) {
player.posY -= 100 * delta;
pressed = true;
} else if (Gdx.input.isKeyPressed(Keys.S)) {
player.posY += 100 * delta;
pressed = true;
}
if (!pressed) {
player.stopAnimation();
}

if(player.posX < 0){
player.posX = 0;
}
if(player.posY < 0){
player.posY = 0;
}
if(player.posX > world.sizeX()*50){
player.posX = world.sizeX()*50;
}
if(player.posY > world.sizeY()*50){
player.posY = world.sizeY()*50;;
}

player.update(delta);
}


Also here a dropbox link with the full code: https://www.dropbox.com/sh/p8umkyiyd663now/AAC4zt716rII-8sQpEbfuNuZa?dl=0

Answer

The problem is that you store player position as integer values. Player velocity is so small after delta calculation that converting float value to integer has a massive impact on speed.

Comparison

Delta position as integer is 2 in case of W and A keys and 1 on S and D.

Delta position as float is around 1.7 in both cases.

Solution: use float values to store player position. Using integer values makes sense only in case of some grid based game.

public float posX;
public float posY;