c++if-statementkbhit

C++ kbhit with if statement lag


I have a strange lag reaction in the game I am making when I use kbhit with if statements. However I do not see this same lag problem occur when I am using a switch statement. Here are both my codes in IF and switch.

This code below causes lag when I try to move the character, I would have to press the button twice in order for the character to move.

void PlayerBike()
{
    if (kbhit())
    {
        if ((getch()) == 'w'){PlayerX = PlayerX - 1;}
        else if ((getch()) == 's'){PlayerX = PlayerX +1;}
        else if ((getch()) == 'd'){PlayerY = PlayerY +1;}
        else if ((getch()) == 'a'){PlayerY = PlayerY - 1;}
    }
}

Switch statement that causes no lag

if (kbhit())
{   
    switch (getch()) 
    {
        case 'w': 
        PlayerX = PlayerX - 1;
        break;

        case 's':
        PlayerX = PlayerX + 1;
        break;

        case 'd':
        PlayerY = PlayerY + 1;
        break;

        case 'a':
        PlayerY = PlayerY - 1;
        break;
    }
}

I would like to use the if statement better since it just looks cleaner.


Solution

  • Every time you call getch, you're waiting for a character of input from the user. If you want to move left, you'd actually have to press the key four times.

    The fix is simple - only call getch() once:

    if (kbhit()) {
        char keystroke = getch();
        if (keystroke == 'w'){PlayerX = PlayerX - 1;}
        else if (keystroke == 's'){PlayerX = PlayerX +1;}
        else if (keystroke == 'd'){PlayerY = PlayerY +1;}
        else if (keystroke == 'a'){PlayerY = PlayerY - 1;}
    }
    

    Incidentally, you had an extra pair of parenthesis around each getch() call. All you need is getch(), not (getch()).