Thursday, July 23, 2015

c++ - Removing delay at start of a key press



I'm making a simple game, and one of the problems I encountered is the annoying delay when pressing a key continuously.


So basically, when I press (for a very long time) for example Up, my object will move 1 unit up, not move (for approx. 1 second), and then move continuously 1 unit up (without any delays).


Currently, I use this to move the object (SDL2):


while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{

case SDLK_UP:
//Move object 1 unit up
break;
//Other unrelated things omitted
}
break;
//Omitted other cases
}
}


What I would like to have is to remove the delay, so that the object can immediately move Up very quickly. Is there any way to do this?



Answer



By waiting for key-down events to be fired, you are likely at the mercy of the key event repeat rate that the OS controls (and which users can specify themselves).


Instead, you may want to call SDL_GetKeyboardState at the top of your game update loop (the part of the update that happens every frame, whether or not an event has come in) to get the state of the keyboard and check that to see if the up key is down or not during any individual frame.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...