Advertisement
thecplusplusguy

SDL frame independent movement

Sep 27th, 2012
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. //http://www.youtube.com/user/thecplusplusguy
  2. //frame independent movement
  3. #include <iostream>
  4. #include <SDL/SDL.h>
  5.  
  6.  
  7. int main()
  8. {
  9.     SDL_Init(SDL_INIT_EVERYTHING);
  10.     SDL_Surface* screen=SDL_SetVideoMode(640,480,32,SDL_SWSURFACE);
  11.     bool running=true;
  12.     SDL_Event event;
  13.     const int SPEED=50;
  14.     Uint32 time;
  15.     float xpos=50.0,ypos=50.0;
  16.     SDL_Rect pos;
  17.     pos.w=30;
  18.     pos.h=30;
  19.     while(running)
  20.     {
  21.         while(SDL_PollEvent(&event))
  22.         {
  23.             if(event.type==SDL_QUIT)
  24.             {
  25.                 running=false;
  26.                 break;
  27.             }
  28.         }
  29.         Uint8* keys=SDL_GetKeyState(0);
  30.         double deltaTimeInSeconds=(SDL_GetTicks()-time)/1000.0;
  31.         if(keys[SDLK_a])
  32.         {
  33.             xpos-=SPEED*(deltaTimeInSeconds);   //v*t, t in seconds
  34.         }
  35.         if(keys[SDLK_s])
  36.         {
  37.             ypos+=SPEED*(deltaTimeInSeconds);   //v*t, t in seconds
  38.         }
  39.         if(keys[SDLK_d])
  40.         {
  41.             xpos+=SPEED*(deltaTimeInSeconds);   //v*t, t in seconds
  42.         }
  43.         if(keys[SDLK_w])
  44.         {
  45.             ypos-=SPEED*(deltaTimeInSeconds);   //v*t, t in seconds
  46.         }
  47.         time=SDL_GetTicks();
  48.         pos.x=xpos;
  49.         pos.y=ypos;
  50.         SDL_FillRect(screen,0,0);
  51.         SDL_FillRect(screen,&pos,SDL_MapRGB(screen->format,255,0,0));
  52.         SDL_Flip(screen);
  53.         //SDL_Delay(10);    //uncomend these, to see, that the square mave with the same speed
  54.         //SDL_Delay(100);
  55.     }
  56.     SDL_Quit();
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement