问题描述
我每秒要运行n次update()
方法,以更新"用户的键盘输入,以便稍后可以在程序的逻辑部分中读取它.因此,我在SDL Docs中找到了两种方法来实现此目的,但我不确定应该使用哪种方法.
I'm running an update()
method n times per second to "update" the keyboard input from the user so I can read it later in the logic part of the program. So I find two ways of implementing this in the SDL Docs and I'm not sure which one should I use.
1;使用SDL_PollEvent搜索所有事件以循环搜索所有按键按下/按下事件,并将按键状态保存在映射中,这样我就可以检查程序逻辑中的每个按键状态.
1; Loop for all events using SDL_PollEvent searching for key down/up events and saving the key states in a map so I can check for each key state in the logic of the program.
注意:或者,我也可以使用SDL_PeepEvents而不是SDL_PollEvent来仅处理重要的事件类型.因此,它不会丢掉"队列中的事件.
Note: Alternatively, I can also use SDL_PeepEvents instead of SDL_PollEvent to take only the event types that matter; so, it would not "thrown away" the events on the queue.
std::map<int, bool> keyboard; // Saves the state(true=pressed; false=released) of each SDL_Key.
void update()
{
SDL_Event event;
while( SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_KEYDOWN:
keyboard[event.key.keysym.sym] = false;
break;
case SDL_KEYUP:
keyboard[event.key.keysym.sym] = true;
break;
}
}
}
2;每帧从键盘拍摄快照,以便我轻松阅读.
2; Taking a snapshot from the keyboard each frame so I can read it easily.
Uint8* keyboard;
void update()
{
SDL_PumpEvents();
keyboard = SDL_GetKeyState(NULL);
}
使用上述任何实现,我都可以像这样阅读keyboard
:
With any of above implementations I can read keyboard
just like this:
if (key_map[SDLK_Return]) printf("Return has been pressed.");
还有,还有另一种方法吗?
Also, is there another way to do so?
推荐答案
我喜欢做1的变体,在其中填充三个数组,不仅指示当前状态,还指示哪些键刚刚按下,哪些键刚刚按下.上升了.这使我可以轻松地在代码中检查那些事件(无需与以前的快照进行比较),但是最重要的是,它不会错过持续时间少于一帧的事件.例如,如果您的游戏由于机器速度慢而以10 fps的速度运行,则用户可能在两次更新例程调用之间按下并释放了一个重要的键,然后您的系统将永远不会对其进行注册.这非常令人沮丧.
I prefer to do a variation of 1, where I fill three arrays, indicating not only the current state, but also which keys just went down and which keys just went up. This allows me to easily check for those events in code (without comparing to the previous snapshot), but, most importantly, it won't miss events that last less than a frame. For example, if your game is running at 10 fps due to a slow machine, the user might press and release an important key between two calls of your update routine, and then your system will never register it. This is extremely frustrating.
当按下键时,SDL还发送键事件,这使您可以在每次按下键时具有多个键按下事件.我发现在通过项目列表实现键盘滚动时,这特别有用.键盘控制的菜单.
SDL also sends key events when the key is held down, which allow you to have multiple key down events for each key up. I find this particularly useful when implementing keyboard scrolling through a list of items, e.g. a keyboard-controlled menu.
这篇关于使用SDL从键盘读取输入的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!