Question

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.

Was it helpful?

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

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top