1
\$\begingroup\$

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)
{
    PingPong.MoveLeftPaddleDown(hWnd);
}

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

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

1 Answer 1

1
\$\begingroup\$

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.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .