Search code examples
javalwjglkeylistener

Transition between right - up, left - down, down - left etc. (JAVA game LWJGL keylistener)


I am making boulderdash remake with LWJGL and Slick2d and i've come across some problem which isn't present in another boulderdash remake I have installed (abandonware Digging Jim - cool) so it means it can be resolved.

I made simple keylistener movement which looks like this

if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
        x += Clock.delta() * speed;
    } else if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)){
        y += Clock.delta() * speed;
    } else if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)){
        x -= Clock.delta() * speed;
    } else if (Keyboard.isKeyDown(Keyboard.KEY_UP)){
        y -= Clock.delta() * speed;
    }

and the problem is that when Im going LEFT I can change direction to DOWN still holding left, but can't change direction to UP. When holding RIGHT i cant go UP or DOWN, when holding UP i can change direction to LEFT and RIGHT no problem.

My question is - how I need to implement this section to work in any way? This feature I believe is crucial to good control system because otherwise player can be stuck in place for a sec and then monster gets you and you're dead. So I'm really asking - how to change direction still holding previous key, so when I'm releasing 2nd key Im going back to 1st direction.


Solution

  • The problem is in your logic which uses "else ifs" instead of simple "ifs". In your code when the LEFT is pressed the "else if" about the DOWN will not be executed. The code should be rewritten as:

        if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
            x += Clock.delta() * speed;
        }  
        if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)){
            y += Clock.delta() * speed;
        }  
        if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)){
            x -= Clock.delta() * speed;
        } 
        if (Keyboard.isKeyDown(Keyboard.KEY_UP)){
            y -= Clock.delta() * speed;
        }