I am programming a simple Ping-Pong game in C++ but I don't know how to handle key presses. At first I intended to use WM_KEYDOWN, but I don't know how to track two pressed keys at once since the window processing function always gets only one wParam right? Basicaly I have two paddles on each side of the screen and when user presses W/S, left paddle moves, when Up/Down keys are pressed, right paddle moves. However when I press two keys at once only one paddle moves.

Another problem is that there is always a short pause after key is pressed - the paddle moves once in desired direction, then pauses and then continues to move. I have no idea why this happens. On the other hand when I use GetAsyncKeyState() like this:

if (GetAsyncKeyState('S') & 0x8000)

everything works as intended - both paddles can move at the same time and there is no short pause on the beginning of movement. On the internet I read everywhere that I should use WM_KEYDOWN insead of GetAsyncKeyState() but how to configure it properly? Thank you

  • \$\begingroup\$ Does MoveLeftPaddleDown perform the movement or just set a flag that is then checked in your update code? \$\endgroup\$ – Tyyppi_77 Jan 24 '18 at 13:40
  • \$\begingroup\$ It performes the movement - changes the Y position of the paddle so paddle is drawn on lower position. \$\endgroup\$ – MPython Jan 24 '18 at 14:05

The issue with using WM_KEYDOWN they way you are using is, that it's only sent once when the key is pressed down and after that in a fixed interval defined by the OS (key repeat events).

So, if you want to make the WM_KEYDOWN approach work like your GetAsyncKeyState approach, you need to set a boolean flag in WM_KEYDOWN, and remove said flag in WM_KEYUP.

Then, in your update method, check the state of the flag, and if it's set, call PingPong.MoveLeftPaddleDown . That way your paddle behaviour will be independent from the operating system's key repeat interval.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.