0

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?

paperbd
  • 153
  • 1
  • 11
  • & 0x8000 <--What's this bit for? – MGZero Jul 06 '11 at 14:37
  • ([link](http://msdn.microsoft.com/en-us/library/ms646293%28v=vs.85%29.aspx)) This page says that "If the most significant bit [of the SHORT] is set, the key is down." So, it's to check the most significant bit. – paperbd Jul 06 '11 at 14:40
  • So shouldn't you be using == 0x8000? I feel like if you step through this, you'll find that part of the decision to be throwing something off. – MGZero Jul 06 '11 at 14:52
  • That should be working, although it will be hard to get any keys to register while single-stepping in the debugger. Doesn't this work in run mode? – Ben Voigt Jul 06 '11 at 15:07
  • 1
    This ought to work. The more traditional way is `if (GetAsyncKeyState('A') < 0)` – Hans Passant Jul 06 '11 at 15:10
  • I'm working more closely with my code and realizing the problem may be elsewhere, with my use of GetForegroundWindow(). I've written this code: `HWND curWin = FindWindow(NULL,TEXT("HavokVisualDebugger")); if (GetForegroundWindow() != curWin) return;` and it seems to return every time it runs. – paperbd Jul 06 '11 at 15:15

2 Answers2

0

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.

Stefan
  • 43,293
  • 10
  • 75
  • 117
0

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.

paperbd
  • 153
  • 1
  • 11