SDL 中的输入(按下按键时)
我想知道如何在 SDL 的 while 循环中检测按键的按下或按键的释放。现在,我知道您可以使用 SDL 获取事件,例如 OnKeyPressed、OnKeyReleased、OnKeyHit 等,但我想知道如何构建像“KeyPressed”这样返回布尔值而不是事件的函数。例子:
while not KeyHit( KEY_ESC )
{
//Code here
}
I would like to know how can I detect the press of a key or release of a key in a while loop in SDL. Now, I know you can get the events with SDL like OnKeyPressed, OnKeyReleased, OnKeyHit, etc, but I want to know how to build functions like 'KeyPressed' that returns a boolean, instead of being an event. Example:
while not KeyHit( KEY_ESC )
{
//Code here
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我知道您已经选择了一个答案..但这里有一些实际代码,说明我通常如何使用一个数组来做到这一点。 :)
首先在某处定义它。
然后创建一个keyboard()函数来注册键盘输入
然后当你真正想要使用键盘输入即handleInput()函数时,它可能看起来像这样:
当然你可以轻松地做你想做的事情要做
**我的网站上的更新版本:**
为了不发布大量源代码,您可以查看 C++ 中的完整 SDL Keyboard 类,该类支持
< a href="http://kennycason.com/posts/2009-09-20-sdl-simple-space-shooter-game-demo-part-i.html" rel="nofollow noreferrer">http://kennycason .com/posts/2009-09-20-sdl-simple-space-shooter-game-demo-part-i.html(如果您有任何问题,请告诉我)
I know you have already selected an answer.. but here is some actual code of how I typically do it with one array. :)
first define this somewhere.
Then later, create a keyboard() function which will register keyboard input
Then when you actually want to use the keyboard input i.e. a handleInput() function, it may look something like this:
And of course you can easily do what you're wanting to do
**Updated version on my website: **
For the sake of not posting a lot of source code, you can view a complete SDL Keyboard class in C++ that supports
http://kennycason.com/posts/2009-09-20-sdl-simple-space-shooter-game-demo-part-i.html (if you have any problems, let me know)
为此有一个 SDL 函数: SDL_GetKeyboardState
检查是否按下了左或右 CTRL 键的示例:
There is an SDL function for this: SDL_GetKeyboardState
Example to check whether left or right CTRL key is pressed:
我在使用 FFI 的 LuaJIT 中遇到了这个问题,这就是我解决它的方法:
全局:
事件代码:
更新函数:
我浪费了大部分时间:
因为 FFI 返回一个 CData 对象,该对象被用作数组键,但它需要整数。
I had this problem in LuaJIT with FFI, this is how I solved it:
Global:
Event code:
Update function:
Most time i wasted on this:
Because FFI is returning a CData object, which was used as the array-key, but it needs the integer.
您应该有 2 个布尔值表作为键。在一张表中,您根据 SDL keydown/keyup 事件设置键 true 或 false,而在另一张表中,您可以使用 false 进行初始化。检查 keyPressed 时,只需将第二个表键与第一个表键进行比较,如果不同,如果第二个表键为 false,则它被按下,否则它被释放。之后,您执行 secondaryTable[key] := 而不是 secondaryTable[key]。作品!
You should have 2 tables of booleans for keys. One table, in which you set keys true or false based on the SDL keydown/keyup events, and another one, that you initialize with false. When checking keyPressed, you just compare the second table key with the first table key, and if different, if second table key is false, then it was pressed, else it was released. After that, you do secondTable[key] := not secondTable[key]. Works!