Hi, i'm quite new to SDL, but i have some problems moving the sprite on keypress.
Here's my code:
Do anybody know whats wrong?Code:#ifdef __cplusplus #include <cstdlib> #else #include <stdlib.h> #endif #ifdef __APPLE__ #include <SDL/SDL.h> #else #include <SDL.h> #endif int main ( int argc, char** argv ) { // initialize SDL video if ( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "Unable to init SDL: %s\n", SDL_GetError() ); return 1; } // make sure SDL cleans up before exit atexit(SDL_Quit); // create a new window SDL_Surface* screen = SDL_SetVideoMode(640, 480, 16, SDL_HWSURFACE|SDL_DOUBLEBUF); if ( !screen ) { printf("Unable to set 640x480 video: %s\n", SDL_GetError()); return 1; } // load an image SDL_Surface* bmp = SDL_LoadBMP("cb.bmp"); if (!bmp) { printf("Unable to load bitmap: %s\n", SDL_GetError()); return 1; } // centre the bitmap on screen int spr1_x = 0, spr1_y = 0; SDL_Rect dstrect; dstrect.x = spr1_x; dstrect.y = spr1_y; // program main loop bool up = false; bool down = false; bool left = false; bool right = false; bool done = false; while (!done) { // message processing loop SDL_Event event; while (SDL_PollEvent(&event)) { // check for messages switch (event.type) { // exit if the window is closed case SDL_QUIT: done = true; break; case SDL_KEYDOWN: { switch (event.key.keysym.sym) { case SDLK_LEFT: left = true; break; case SDLK_RIGHT: right = true; break; case SDLK_UP: up = true; break; case SDLK_DOWN: down = true; break; case SDLK_ESCAPE: done = true; break; default: break; } } case SDL_KEYUP: switch( event.key.keysym.sym ) { case SDLK_LEFT: left = false; break; case SDLK_RIGHT: left = false; break; case SDLK_UP: left = false; break; case SDLK_DOWN: left = false; break; default: break; } } // end switch } // end of message processing if (left) {spr1_x -= 1;} if (right) {spr1_x += 1;} if (up) {spr1_y -= 1;} if (down) {spr1_y += 1;} // DRAWING STARTS HERE // clear screen SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0)); // draw bitmap SDL_BlitSurface(bmp, 0, screen, &dstrect); // DRAWING ENDS HERE // finally, update the screen :) SDL_Flip(screen); } // end main loop // free loaded bitmap SDL_FreeSurface(bmp); // all is well ;) printf("Exited cleanly\n"); return 0; }


Reply With Quote

Bookmarks