c++inputgetchkbhit

c++ tron Player lightcycle move in one direction


I am trying to have the player lightcycle keep moving in one direction without stopping until the player pushes a button to move it in another direction. I am not sure how I could do this with kbhit so please give me some advice! thanks.

void Lightcycle(){
    if (kbhit()) {// get user key input
    char GetCh = getch(); // GetCh equal to the button the user presses
    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;}
}// end kbhit
}// end function

Solution

  • I guess you'll need a global variable called direction and change that, like:

    if (GetCh == 'w'){direction=1;}
    else if (GetCh == 's'){direction=2;}
    else if (GetCh == 'd'){direction=3;}
    else if (GetCh == 'a'){direction=4;}
    

    Then you'll need, somewhere in your game loop, to handle the player movement constatly, like:

    while(gameRunning){
        // Random code handling game goes here
        ...
        if (direction== 1){PlayerX = PlayerX - 1;}
        else if (direction== 2){PlayerX = PlayerX +1;}
        else if (direction== 3){PlayerY = PlayerY +1;}
        else if (direction== 3){PlayerY = PlayerY - 1;}
        ...
        // Other code handling game goes here
    }