A while ago I downloaded a demo that renders some terrain and allows you to move an FPS camera around it using the keyboard. The handler for the KeyDown event looked something like this:
void MyApp_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
camera.Walk(0.5f);
// Handle other keys similarly
}
I compiled and ran the demo but the camera movement was extremely choppy. I then decided to change it to this:
// This is a member of MyApp
bool keys[256];
void MyApp_KeyDown(object sender, KeyEventArgs e)
{
keys[(int)e.KeyCode] = true;
}
void MyApp_KeyUp(object sender, KeyEventArgs e)
{
keys[(int)e.KeyCode] = false;
}
// In the Update/Render function:
if (keys[(int)Keys.W])
camera.Walk(0.5f);
// Handle other keys similarly
After this change the movement was completely smooth.
My reasoning for doing this was that the handlers are called each time a key is pressed/released and so they must return very quickly so they can be called for the next key press/release.
My question is - am I thinking about this correctly? The reason I ask is:
1) The previous code in the handlers really didn't do much, so I would expect it to be executed fast enough for this not to be a problem.
2) I see many people that use the first method (in tutorials, posts, etc.) and none of them are complaining about choppiness.
BTW, the demo used C# and MDX but I guess the question is valid for any Windows Forms application, and also for Win32 applications and the window procedure (maybe especially there because that function is called for many other events as well).
Any help is greatly appreciated.