win32上的异步键盘输入
我正在 Windows 7 上使用免费版本的 Havok 物理引擎用 C++ 创建一个简单的 3D 游戏。我想使用 WASD 键来移动角色。代码的结构是这样的,我需要异步捕获这个输入;场景的每一帧都会调用一个函数来更新角色的位置(我想尝试检查当前是否按下了某个键,而不是使用某种事件侦听器)。我四处寻找一个好的解决方案,因为我对 win32 函数知之甚少,并将其放在一起:
if (GetAsyncKeyState(0x41) & 0x8000) posX=-1.0f; //A
if (GetAsyncKeyState(0x44) & 0x8000) posX=1.0f; //D
if (GetAsyncKeyState(0x57) & 0x8000) posX=1.0f; //W
if (GetAsyncKeyState(0x53) & 0x8000) posX=-1.0f; //S
在检查了一些 printf 语句后,可视化调试器似乎没有拾取任何输入。我知道 WM_KEYDOWN 和 WM_KEYUP,但我找不到如何使用它们的简单解释,据我所知,它们更多是基于事件的而不是异步的。
上面的代码片段有问题吗?或者我应该尝试其他方法?
I'm creating a simple 3D game on Windows 7 in C++ using the free version of the Havok physics engine. I want to use the WASD keys to move the character. The structure of the code is such that I need to capture this input asychronously; there is a function called in every frame of the scene to update the character's position (I want to try checking if a key is currently pressed instead of using some kind of listener for events). I searched around for a good solution, as I know little to nothing about win32 functions, and put this together:
if (GetAsyncKeyState(0x41) & 0x8000) posX=-1.0f; //A
if (GetAsyncKeyState(0x44) & 0x8000) posX=1.0f; //D
if (GetAsyncKeyState(0x57) & 0x8000) posX=1.0f; //W
if (GetAsyncKeyState(0x53) & 0x8000) posX=-1.0f; //S
After checking with some printf statements, the visual debugger doesn't seem to be picking up any input with this. I know of WM_KEYDOWN and WM_KEYUP, but I can't find simple explanations on how to use them, and as far as I can tell they are more event-based than asynchronous.
Is there a problem with the snippet above, or should I try another approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最佳猜测:您正在检查“
A
”而不是“a
”。当然,除非您也按住 Shift 键,否则仅按 a 键不会触发您的代码。Best guess: You're checking for "
A
" instead of "a
". Unless of course you hold down the shift key as well, just pressing the a-key won't trigger your code.看来我的问题毕竟不是 GetAsyncKeyState() ,而是我对 FindWindow() 和 GetWindowRect() 的使用。它无法识别当前窗口是可视化调试器。固定的。
It appears that my problem wasn't GetAsyncKeyState() after all, but my use of FindWindow() and GetWindowRect(). It wasn't recognizing that the current window was the visual debugger. Fixed.