Telash
Telash

Reputation: 3

C SDL Object movement flow

I just started with SDL and made a small square moving around on a window. I used DL_GetKeyboardState, and got it moving kind of smoothly. However, just when I start moving it one direction by holding down one key, it moves a bit, stops, then move like I want. This messes up the smoothness. My best guess is that it waits for a doubleclick from the mouse, but im not sure. Any suggestions?

The code:

#include <stdio.h>
#include <SDL.h>

int main(int argc, char * argv[])
{
   SDL_Window *window;
   SDL_Renderer *renderer;
   SDL_Event event;

   SDL_Init(SDL_INIT_VIDEO);
   window = SDL_CreateWindow("Yelda!", SDL_WINDOWPOS_UNDEFINED,        SDL_WINDOWPOS_UNDEFINED, 1600, 1200, 0);
   renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

   const Uint8 *state;
   int run = 1;
   int xpos=300;
   int ypos=300;
   int projectileYPos;
   int projectileXPos;
   int loop;
   int lanceLength = 10;

   while(run)
   {
      while(SDL_PollEvent(&event))
      {
         state=SDL_GetKeyboardState(NULL);

         if(state[SDL_SCANCODE_ESCAPE])
            run=0;
         if(state[SDL_SCANCODE_W])
            ypos-=10;
         if(state[SDL_SCANCODE_S])
            ypos+=10;
         if(state[SDL_SCANCODE_A])
            xpos-=10;
         if(state[SDL_SCANCODE_D])
            xpos+=10;

         SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
         SDL_RenderClear(renderer);
         SDL_SetRenderDrawColor(renderer, 255, 255, 255 ,255);
         SDL_Rect rect = {xpos, ypos, 20, 20 };
         SDL_RenderFillRect(renderer, &rect);
         SDL_RenderPresent(renderer);

         SDL_Delay(20);
      }
   }

   SDL_DestroyWindow(window);
   SDL_DestroyRenderer(renderer);
   SDL_Quit();
   return 0;
}

Upvotes: 0

Views: 267

Answers (1)

flogram_dev
flogram_dev

Reputation: 42858

The SDL wiki says that you should use SDL_PumpEvents() to update the keyboard state array.

And indeed, if we

  • remove the while(SDL_PollEvent(&event)) loop (not its contents) as it's unneeded,
  • move state=SDL_GetKeyboardState(NULL); before the while(run) loop (the address of the array "will be valid for the whole lifetime of the application", so it always returns the same pointer), and
  • only call SDL_PumpEvents() inside the loop,

then the movement is smooth.

Upvotes: 0

Related Questions