(C++) SDL example 3: moving a sprite over a background
February 24, 2017 · View on GitHub
(C++) SDL example 3: moving a sprite over a background
This SDL example shows a sprite moving a over a background, like this screenshot (png).
Operating system: Ubuntu
IDE: Qt Creator 2.0.0
Project type: Qt4 Console Application
Selected required modules: QtCore
Qt project file
#------------------------------------------------- # # Project created by QtCreator 2010-07-17T14:57:33 # #------------------------------------------------- QT += core QT -= gui TARGET = CppSdlExample3 CONFIG += console CONFIG -= app_bundle TEMPLATE = app LIBS += -L/usr/local/lib -lSDL SOURCES += main.cpp
Source code
#include <cassert> #include <cstdlib> #include <SDL/SDL.h> int main() { //Start SDL if (SDL_Init( SDL_INIT_EVERYTHING ) < 0) { assert(!"Should not get here. Initialization failed"); } //Call SDL_Quit upon exit std::atexit(SDL_Quit); //Load background SDL_Surface * const background = SDL_LoadBMP( "Background.bmp"); assert(background && "Assume background image is found in same folder as binary"); assert(background->w > 100); assert(background->h > 100); //Set up screen, same size as background SDL_Surface * const screen = SDL_SetVideoMode(background->w,background->h, 32, SDL_SWSURFACE ); assert(screen && "Assume screen can be initialized"); //Load sprite SDL_Surface * const sprite = SDL_LoadBMP("Butterfly.bmp"); SDL_SetColorKey(sprite, SDL_SRCCOLORKEY | SDL_RLEACCEL,SDL_MapRGB(sprite->format,0,255,0)); assert(sprite && "Assume sprite image is found in same folder as binary"); //Create a sprite rect, same dimensions as sprite image SDL_Rect sprite_rect; sprite_rect.x = 0; sprite_rect.y = 0; sprite_rect.h = sprite->h; sprite_rect.w = sprite->w; int dx = 1; //Horizontal speed int dy = 1; //Vertical speed //Blit background to screen SDL_BlitSurface( background, 0, screen, 0); while (1) { //Remove-blit image from screen SDL_BlitSurface( background, &sprite_rect, screen, &sprite_rect); //Move sprite sprite_rect.x+=dx; sprite_rect.y+=dy; //Make sprite bounce if (sprite_rect.x < 0) dx=-dx; if (sprite_rect.x + sprite_rect.w > screen->w) dx=-dx; if (sprite_rect.y < 0) dy=-dy; if (sprite_rect.y + sprite_rect.h > screen->h) dy=-dy; //Blit image to screen SDL_BlitSurface( sprite, 0, screen, &sprite_rect); //Update screen SDL_Flip( screen ); //Wait for user to close window SDL_Event event; SDL_PollEvent(&event); if (event.type == SDL_QUIT) break; } //Free the loaded image SDL_FreeSurface( background ); }