c ++ tron播放器lightcycle向一个方向移动

时间:2013-11-17 23:53:23

标签: c++ input getch kbhit

我试图让玩家的光循环继续向一个方向移动而不停止,直到玩家按下按钮将其向另一个方向移动。我不知道怎么能用kbhit做到这一点所以请给我一些建议!谢谢。

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

1 个答案:

答案 0 :(得分:2)

我想你需要一个名为direction的全局变量并改变它,如:

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

然后你需要在游戏循环的某个地方不断地处理玩家的运动,例如:

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
}