[SDL] SDL event behavior

Ivan Stankovic pokemon at fly.srk.fer.hr
Tue Jan 14 09:30:00 PST 2003


On Tue, Jan 14, 2003 at 06:15:40PM +0800, Michael Alger wrote:
> On Mon, Jan 13, 2003 at 08:16:16PM -0800, Chris Thielen wrote:
> The usual way of handling input for games is to disable key repeating,
> and just catch the KEYDOWN/KEYUP event and use a flag to keep track of
> the state of the key.   You then do the sprite movement outside of the
> event handler code based on what controls are currently being applied.
> 
> Typically, this is done using a bitfield to save memory.
> 
> For example:
> 
> #define KEY_LEFT    (1 << 0)  /* you can also count in powers of two */
> #define KEY_RIGHT   (1 << 1)  /* yourself here, but i find this more */
> #define KEY_UP      (1 << 2)  /* readable. YMMV. */
> #define KEY_DOWN    (1 << 3)
> 
> int keys = 0;
> 
> while (SDL_PollEvent(&event) > 0)
> {
>   switch (event.type)
>   {
>     case SDL_KEYDOWN:
>       switch (event.key.keysym.sym)
>       {
>         case SDLK_LEFT:   /* set flag to indicate left arrow is down */
>           keys |= KEY_LEFT;
>           break;
>         case SDLK_RIGHT:  /* set flag to indicate right arrow is down */
>           keys |= KEY_RIGHT;
>           break;
>       }
>       break;
>     case SDL_KEYUP:
>       switch (event.key.keysym.sym)
>       {
>         case SDLK_LEFT:   /* clear left arrow flag */
>           keys &= ~KEY_LEFT;
>           break;
>         case SDLK_RIGHT:  /* clear right arrow flag */
>           keys &= ~KEY_RIGHT;
>           break;
>       }
>       break;
>   }
> }
> 
> if (keys & KEY_LEFT)
>   /* rotate ship "left" */
> if (keys & KEY_RIGHT)
>   /* right ship "right" */

There is an easier way to do this: use SDL_GetKeyState().

Uint8 *keys;
 
SDL_PumpEvents();
keys = SDL_GetKeyState(NULL);

if(keys[SDLK_LEFT])
	/* rotate ship left */


Hope that helps.

-- 
Ivan Stankovic, pokemon at fly.srk.fer.hr




More information about the SDL mailing list