我使用的是 SDL 2.0,但无法让 SDL_GetKeyboardState
按预期工作。玩家应该上下移动,但这种情况没有发生。
void Movements() {
const Uint8 *currentKey = SDL_GetKeyboardState(NULL); // Point has to be defined once
if (currentKey[SDLK_w]){
PlayerPaddle.y = PlayerPaddle.y+2;
}
if (currentKey[SDLK_s]){
PlayerPaddle.y = PlayerPaddle.y+2;
}
}
int main(int argc, char* args[]) {
main_menue();
bool running = true;
while (running == true) {
SDL_PollEvent(&occur);
if (occur.type == SDL_QUIT) { // Closes the window, if user stops running
running = false;
}
Movements();
}
}
我还尝试使用 PumpEvents 来启动事件循环,但仍然无法读取按键的当前状态。我还在 stackoverflow ( SDL_GetKeyboardState not working ) 上找到了这个,但那里的答案并没有帮助我找到解决方案。我在这里错过了什么吗?难道我真的瞎了眼,误解了什么吗?
最佳答案
假设 SDL_Init()
和其他声明在粘贴到此处时刚刚被删除。
首先,您没有使用正确的索引。 正如所解释的in the documentation here :“此数组的索引是通过使用 SDL_Scancode values 获得的。”但您正在使用 SDL_Keycode 值。
另一个问题是您使用非阻塞 SDL_PollEvent
并在每次迭代时调用 Movements()
,并且没有任何类型的阻塞或等待在你的循环中。这将使用 100% CPU,尽可能快地运行,最终您将得到相当高的 y
值...
您可以使用按键事件,而不是由 SDL_GetKeyboardState
返回的数组。例如,如果 occurr.type
是 SDL_KEYDOWN
,则 occurr.key.keysym.sym
是按下的 SDL_Keycode
key 。看SDL_Event
的文档以及其他事件类型的详细信息。
您还应该将 SDL_Delay
添加到循环中。
另一种方法是使用 SDL_WaitEvent
仅当事件发生时才返回。然后处理该事件,如果是按键,则根据按键执行一些操作,等等...
关于c++ - SDL_GetKeyboardState 不返回按键的当前状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27493378/