tags:

views:

399

answers:

2

Here is the problem, I have written an event loop to detect keydown and keyup events. The problem I am running into is that a keydown event is generating a keydown and a keyup event when the key is pressed and held down. I am using the arrow keys to move an object and then to stop moving when the key is released(keyup). Any help would well help. Thanks. =)

Justin

P.S. I would post the code but I can't get it to look right.

print("      SDL_Event event;
 SDL_EnableKeyRepeat(0,0);
 while(SDL_PollEvent(&event)){
  switch(event.type){
  case SDL_QUIT:
   done = true;
   break;
  case SDL_KEYDOWN:
   switch(event.key.keysym.sym){
   case SDLK_ESCAPE:
    done = true;
    break;
   case SDLK_LEFT:
    animate_x = -5;
    cout << "left press\n";
    break;
   case SDLK_RIGHT:
    animate_x = 5;
    break;
   case SDLK_UP:
    animate_y = -5;
    break;
   case SDLK_DOWN:
    animate_y = 5;
    break;
   default:
    break;
   }
   break; -left out in original
  case SDL_KEYUP:
   switch(event.key.keysym.sym){
   case SDLK_LEFT:
    cout << "left up\n";
    animate_x = 0;
    break;
   case SDLK_RIGHT:
    animate_x = 0;
    break;
   case SDLK_UP:
    animate_y = 0;
    break;
   case SDLK_DOWN:
    animate_y = 0;
    break;
   default:
    break;
   }
   break; -left out in original
  }
 }");

While trying to figure out how to post code I noticed that I had left out a default in two of the cases. The code now works. It kept going through the cases and executing the code that matched what was in the queue. Silly me. Thanks for all the help. =)

+2  A: 

It looks like you have key repeat enabled. To disable it, use

SDL_EnableKeyRepeat(0, 0);
Joh
That didn't work in my case because the problem was with the switch statement. My code shows it in there but if you comment it out it doesn't affect anything. Thanks for the suggestion it caused me to think about this problem a little differently. =)
+1  A: 

You might want to use SDL_GetKeyState instead of keeping track of keydown/keyup; I use it for detecting the instant state of keys, which you can use to determine if keys are being held down over successive frames.