所以我有一个函数可以处理我在OpenGL中处理的游戏中的按键操作。但是,问题在于,即使我已经制作了两个正方形,并且当按下正确的键时它们都移动,但只移动了一个正方形。有没有办法让两个方块移动。这是我所说的glutKeyboardFunc函数:
void handleKeypress(unsigned char key, int x, int y)
{
if (key == 'w')
{
for (int i = 0; i < 12; i++)
{
if (i == 1 || i == 7 || i == 10 || i == 4)
{
square[i] = square[i] + 0.1;
}
}
}
if (key == 'd')
{
for (int i = 0; i < 12; i++)
{
if (i == 0 || i % 3 == 0)
{
square[i] = square[i] + 0.1;
}
}
}
if (key == 's')
{
for (int i = 0; i < 12; i++)
{
if (i == 1 || i == 7 || i == 10 || i == 4)
{
square[i] = square[i] - 0.1;
}
}
}
if (key == 'a')
{
for (int i = 0; i < 12; i++)
{
if (i == 0 || i % 3 == 0)
{
square[i] = square[i] - 0.1;
}
}
}
glutPostRedisplay();
}
如果您需要更多代码,请询问。
答案 0 :(得分:1)
编辑以下评论。
// I'm making some assumptions about your functions here. Make adjustments.
// You can handle both players' key inputs here.
void handleKeypress(unsigned char key, int x, int y)
{
if (key == 27)
exit(0);
// Player 1
if (key == 'w')
{
A.moveSquareUp();
}
if (key == 'd')
{
A.moveSquareRight();
}
if (key == 's')
{
A.moveSquareDown();
}
if (key == 'a')
{
A.moveSquareLeft();
}
}
void handleSpecialKeypress(int key, int x, int y)
{
// Player 2
if (key == GLUT_KEY_UP)
{
B.moveSquareUp();
}
if (key == GLUT_KEY_RIGHT)
{
B.moveSquareRight();
}
if (key == GLUT_KEY_DOWN)
{
B.moveSquareDown();
}
if (key == GLUT_KEY_LEFT)
{
B.moveSquareLeft();
}
}
您需要在游戏逻辑中的某个位置处理键盘事件(主循环或来自glutKeyboardFunc()
的回调),并调用所需的行为。这有一些优点:
if
代替switch
可以使用多个密钥。