0

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.

John Odom
  • 1,189
  • 2
  • 20
  • 35
ssj3goku878
  • 745
  • 3
  • 14
  • 43

3 Answers3

4

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()).

Scott Mermelstein
  • 15,174
  • 4
  • 48
  • 76
3

Your if code calls getch more than once, which is not what you want.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
2

It's because in your multiple if/else if statements it will call getch more than once if the last if statement failed. What you could do instead is this:

if(kbhit())
{
    char chInput = getch();

    if (chInput == 'w'){PlayerX = PlayerX - 1;}
    else if (chInput == 's'){PlayerX = PlayerX +1;}
    else if (chInput == 'd'){PlayerY = PlayerY +1;}
    else if (chInput == 'a'){PlayerY = PlayerY - 1;}
}

This will only call getch once then check with character key was pressed.

John Odom
  • 1,189
  • 2
  • 20
  • 35