1
\$\begingroup\$

In my slick-based game, I have 4 states - introState, gameState, pauseState and menuState.

From the gameState, I want player to go to either menuState or pauseState. To do that, I did this in gameState:-

public void changeState(GameContainer gc, StateBasedGame sbg)
{
    Input input = gc.getInput();
    if(input.isKeyPressed(Keyboard.KEY_ESCAPE))
    {
        sbg.enterState(2);
    }
    else if(input.isKeyPressed(Keyboard.KEY_SPACE))
    {
        sbg.enterState(3);
    }
}

To return from pauseState to gameState, I did this in pauseState:-

public void changeState(GameContainer gc, StateBasedGame sbg)
{
    Input input = gc.getInput();
    if(input.isKeyPressed(Keyboard.KEY_ESCAPE))
    {
        sbg.enterState(1);
    }
}

To return from menuState to gameState, I did this in menuState:-

public void changeState(GameContainer gc, StateBasedGame sbg)
{
    Input input = gc.getInput();
    if(input.isKeyPressed(Keyboard.KEY_SPACE))
    {
        sbg.enterState(1);
    }
}

As you can see, I want player to go to either pauseState or menuState from the gameState and not from pauseState to menuState or vice-versa.

Unfortunately, due to some unknown reason, when i press escape, it enters pauseState correctly but then if i press spacebar and then press enter, instead of going to gameState it goes to menuState. Any idea why is that happening?

\$\endgroup\$
3
\$\begingroup\$

I found the solution myself:- Before going to a different state, use the input.clearKeyPressedRecord() to clear all previously recorded key-Presses, or else even after changing a state, previously stored keyPress event will cause problems.

So instead of doing this,

public void changeState(GameContainer gc, StateBasedGame sbg)
{
    Input input = gc.getInput();
    if(input.isKeyPressed(Keyboard.KEY_ESCAPE))
    {
        sbg.enterState(1);
    }
}

Do this:

public void changeState(GameContainer gc, StateBasedGame sbg)
{
    Input input = gc.getInput();
    if(input.isKeyPressed(Keyboard.KEY_ESCAPE))
    {
        input.clearKeyPressedRecord();
        sbg.enterState(1);
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.