0
\$\begingroup\$

In short, I am trying to avoid my keys from sticking when its in the gameover state. The problem is if the player is holding down the right button for instance and dies, then he restarts the game moving right indefinitely until the player presses down the right button again. How can I prevent this from occuring? I tried setting up a boolean variable that detects if it's pressed or not but that isn't working.

else if(state == STATE.GAMEOVER)
    {
        gameover.tick();
        MouseInput.pressed = true;
        KeyInput.pressed = false;
    }


public void keyPressed(KeyEvent e)
{
    int key = e.getKeyCode();

    for (int i = 0; i < handler.object.size(); i++)
    {
        GameObject tempObject = handler.object.get(i);

        if(tempObject.getId() == ID.Player && pressed == true) 
        {
            if (key == KeyEvent.VK_W) handler.setUp(true);
            if (key == KeyEvent.VK_S) handler.setDown(true);
            if (key == KeyEvent.VK_A) handler.setLeft(true);
            if (key == KeyEvent.VK_D) handler.setRight(true);
        }
        if (key == KeyEvent.VK_ESCAPE && pressed == true)
        {
            Game.setState(Game.STATE.PAUSE);
        }
    }
}
public void keyReleased(KeyEvent e)
{
    int key = e.getKeyCode();

    for (int i = 0; i < handler.object.size(); i++)
    {
        GameObject tempObject = handler.object.get(i);

        if(tempObject.getId() == ID.Player && pressed == true) 
        {
            if (key == KeyEvent.VK_W) handler.setUp(false);
            if (key == KeyEvent.VK_S) handler.setDown(false);
            if (key == KeyEvent.VK_A) handler.setLeft(false);
            if (key == KeyEvent.VK_D) handler.setRight(false);
        }           
    }
}
public static boolean isPressed() 
{
    return pressed;
}
public static void setPressed(boolean pressed) 
{
    KeyInput.pressed = pressed;
}

    if(handler.isUp() && KeyInput.pressed == true) velY = -5;
    else if(!handler.isDown() && KeyInput.pressed == true) velY = 0;

    if(handler.isDown() && KeyInput.pressed == true) velY = 5;
    else if(!handler.isUp() && KeyInput.pressed == true) velY = 0;

    if(handler.isRight() && KeyInput.pressed == true) velX = 5;
    else if(!handler.isLeft() && KeyInput.pressed == true) velX = 0;

    if(handler.isLeft() && KeyInput.pressed == true) velX = -5;
    else if(!handler.isRight() && KeyInput.pressed == true) velX = 0;
}
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Did you try clearing the player's directions when entering the game over state? Something like this:

else if(state == STATE.GAMEOVER)
{
    gameover.tick();
    MouseInput.pressed = true;
    KeyInput.pressed = false;
    player.setUp(false);
    player.setDown(false);
    player.setLeft(false);
    player.setRight(false);
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .