函数设计 要求:对创建的void userKey()函数贴出对应代码和注释,代码为:void userKey() { t2 = GetTickCount();//获取当前系统的运行时间 if (GetAsyncKeyState(VK_UP))//向上键 { player.y -= PLAYER_SPEED; if (player.y < 0) { player.y = 0; } } else if (GetAsyncKeyState(VK_DOWN))//向下键 { player.y += PLAYER_SPEED; if (player.y > WIN_HEIGHT - PLAYER_HEIGHT) { player.y = WIN_HEIGHT - PLAYER_HEIGHT; } } else if (GetAsyncKeyState(VK_LEFT))//向左键 { player.x -= PLAYER_SPEED; if (player.x < -PLAYER_WIDTH / 2) { player.x = -PLAYER_WIDTH / 2; } } else if (GetAsyncKeyState(VK_RIGHT))//向右键 { player.x += PLAYER_SPEED; if (player.x > WIN_WIDTH - PLAYER_WIDTH / 2) { player.x = WIN_WIDTH - PLAYER_WIDTH / 2; } } if (GetAsyncKeyState(VK_SPACE) && t2 - t1 > 300) { createBullet();//创建玩家子弹 HANDLE hThread = CreateThread(NULL, 0, playMusic, NULL, NULL, NULL); t1 = t2; } }
时间: 2024-02-29 13:54:37 浏览: 82
这是一个用于处理用户键盘输入的函数,具体实现如下:
```c++
void userKey() {
// 获取当前系统的运行时间
t2 = GetTickCount();
if (GetAsyncKeyState(VK_UP)) { // 向上键
player.y -= PLAYER_SPEED;
if (player.y < 0) {
player.y = 0;
}
} else if (GetAsyncKeyState(VK_DOWN)) { // 向下键
player.y += PLAYER_SPEED;
if (player.y > WIN_HEIGHT - PLAYER_HEIGHT) {
player.y = WIN_HEIGHT - PLAYER_HEIGHT;
}
} else if (GetAsyncKeyState(VK_LEFT)) { // 向左键
player.x -= PLAYER_SPEED;
if (player.x < -PLAYER_WIDTH / 2) {
player.x = -PLAYER_WIDTH / 2;
}
} else if (GetAsyncKeyState(VK_RIGHT)) { // 向右键
player.x += PLAYER_SPEED;
if (player.x > WIN_WIDTH - PLAYER_WIDTH / 2) {
player.x = WIN_WIDTH - PLAYER_WIDTH / 2;
}
}
if (GetAsyncKeyState(VK_SPACE) && t2 - t1 > 300) { // 空格键
createBullet(); // 创建玩家子弹
HANDLE hThread = CreateThread(NULL, 0, playMusic, NULL, NULL, NULL); // 创建线程播放音效
t1 = t2;
}
}
```
该函数的作用是监听用户在键盘上的操作,根据用户的输入来更新玩家的位置,并在用户按下空格键时创建玩家子弹并播放音效。其中 `GetAsyncKeyState()` 函数用于检测对应的按键是否被按下,`createBullet()` 函数用于创建玩家子弹,`CreateThread()` 函数用于创建一个新的线程来播放音效。
阅读全文