Search code examples
cinputsdlgame-development

How to get constant User Input with SDL?


I am trying to code a game in C using SDL. The problem is the keyboard inputs are not constant. If i press a key the player moves a step, pauses and then it moves fluidly. It is like I am in a text document and hold down one key. I tried using SDL_GetKeyboardState() and I also tried using SDL_PollEvent() and then do event.key.keysym.sym == ... but with both I have the same Issue. Edit: Here are my structs:

typedef struct 
{
  SDL_Rect rect;
  bool alive, large;
  float speed;

} Player;

typedef struct
{
  bool running;
  int width, height;
  SDL_Event event;
  Uint8* keystates;
  Player* player;
} Game;

Here is the function that handles the input:

void update(Game* game)
{
  game->keystates = SDL_GetKeyboardState(NULL);


  // set player speed
  game->player->speed = STD_PLAYERSPEED * (game->player->large ? 2 : 1);

  if( SDL_PollEvent(&game->event) > 0 )
  {
    switch(game->event.type)
    {
      case SDL_QUIT:
        game->running = false;
        break;  
    }

    if(game->keystates[SDL_SCANCODE_W])
    {
      game->player->rect.y -= game->player->speed;
    }
    if(game->keystates[SDL_SCANCODE_S])
    {
      game->player->rect.y += game->player->speed;
    }

    if(game->keystates[SDL_SCANCODE_A])
    {
      game->player->rect.x -= game->player->speed;
    }
    if(game->keystates[SDL_SCANCODE_D])
    {
      game->player->rect.x += game->player->speed;
    }
  }
}

Solution

  • Answer from @HolyBlackCat: First, SDL_PollEvent must be used as while (SDL_PollEvent(...))', not 'if (SDL_PollEvent()). Second, if(game->keystates[SDL_SCANCODE_W]) must be outside of this while/if. Correct Code:

    void update(Game* game)
    {
      game->keystates = SDL_GetKeyboardState(NULL);
    
    
      // set player speed
      game->player->speed = STD_PLAYERSPEED * (game->player->large ? 2 : 1);
    
      while( SDL_PollEvent(&game->event) > 0 )
      {
        switch(game->event.type)
        {
          case SDL_QUIT:
            game->running = false;
            break;  
        } 
      }
    
      if(game->keystates[SDL_SCANCODE_W])
      {
        game->player->rect.y -= game->player->speed;
      }
      if(game->keystates[SDL_SCANCODE_S])
      {
        game->player->rect.y += game->player->speed;
      }
      if(game->keystates[SDL_SCANCODE_A])
      {
        game->player->rect.x -= game->player->speed;
      }
      if(game->keystates[SDL_SCANCODE_D])
      {
        game->player->rect.x += game->player->speed;
      }
    }