You are on page 1of 7

DrawingSpriteswithSDL

Note:ThistutorialassumesthatyoualreadyknowhowtodisplayawindowwithSDL.

LoadingandDrawingSprites
TodisplayaspriteinSDL,youfirstneedtoloadabitmapfile.Thistaskisaccomplished
usingSDL_LoadBMP(),whichtakesthenameofthebitmapfileyouwanttoloadand
returnsapointertoasurfacethatstoresthebitmap'sdata.
YoudrawthebitmapusingSDL_BlitSurface(),whichtakesfourparameters.Thefirst
isapointertothesourcesurface,whichyougotfromSDL_LoadBMP().
ThesecondisanSDL_Rectstoringthelocationinthesourcebitmapofthespriteyou
wantdrawn.TheSDL_Rectisaverysimplestructure.Itjuststoresanx,yvaluepairas
wellaswidthandheightvalues.
Onethingyouneedtoknowbeforegoingonisthatincomputergraphics,apositivey
valuealmostalwaysmeansdown.Startingfromthetopofthescreenandgoingdown,
youwouldgo(0,0)>(0,1)>(0,2),etc.
Thethirdparameterisapointertothescreensurface,whichyougotfrom
SDL_SetVideoMode().
ThelastparameterisanSDL_Rect storingwhereyouwanttheimagedrawntoonthe
screen.
Althoughyoucandrawtheentirebitmapatonce,mostofthetimeyou'llonlywantto
drawpartsofthebitmap.Thisisbecausemostbitmapsusedin2Dgamesstoremore
thanoneimage.
Theterm"blit"standsfor"blockimagetransfer",incaseyouwantedtoknow.
AcalltoSDL_BlitSurface()willlooklikethis(assumethatbitmapisapreviously
loadedsurfaceandthatscreenisthescreensurface):
// Part of the bitmap that we want to draw
SDL_Rect source;
source.x = 24;
source.y = 63;
source.w = 65;
source.h = 44;

// Part of the screen we want to draw the sprite to


SDL_Rect destination;
destination.x = 100;
destination.y = 100;
destination.w = 65;
destination.h = 44;
SDL_BlitSurface(bitmap, &source, screen, &destination);
Beforedrawingasurface,wealmostalwaysneedtofillinSDL_Rectstructurestospecify
whatwewantdrawnandwherewewantitdrawnto.Theonlytimeswedon'tneedtofill
thesestructuresiniswhenwewanttheentiresurfacedrawn.Inthiscase,wejustpass
inNULL.
Oncewe'vedrawneverythingweneedto,wehavetocallSDL_Flip() totellSDLto
displayourscene.WepassSDL_Flip()ourscreensurfaceasaparameter.
Hereisthecodetoloadawindowanddrawasprite.Mostofthecodeisfromtheprevious
tutorial,soI'veboldedthepartsrelatedtodrawingthesprite.ThebitmapI'veusedcan
bedownloadedhere.Makesuretoputitinyourmainprojectdirectorybeforerunning
thecode.

#include "SDL.h"
const int WINDOW_WIDTH = 640;
const int WINDOW_HEIGHT = 480;
const char* WINDOW_TITLE = "SDL Start";
int main(int argc, char **argv)
{
SDL_Init( SDL_INIT_VIDEO );
SDL_Surface* screen = SDL_SetVideoMode( WINDOW_WIDTH,
WINDOW_HEIGHT, 0,
SDL_HWSURFACE | SDL_DOUBLEBUF );
SDL_WM_SetCaption( WINDOW_TITLE, 0 );
SDL_Surface* bitmap = SDL_LoadBMP("bat.bmp");
// Part of the bitmap that we want to draw
SDL_Rect source;
source.x = 24;
source.y = 63;
source.w = 65;
source.h = 44;
// Part of the screen we want to draw the sprite to
SDL_Rect destination;

destination.x
destination.y
destination.w
destination.h

=
=
=
=

100;
100;
65;
44;

SDL_Event event;
bool gameRunning = true;
while (gameRunning)
{
if (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
gameRunning = false;
}
}
SDL_BlitSurface(bitmap, &source, screen, &destination);
SDL_Flip(screen);
}
SDL_FreeSurface(bitmap);
SDL_Quit();
return 0;
}
Therearetwothingstomakenoteofinthecodeabove.Oneisthatyoushouldfreeany
surfacesthatyoucreateyourself.Theotheristhatyouneedtodrawyourentirescene
beforecallingSDL_Flip().ThecalltoSDL_Flip()shouldbethelastcallinyour
renderingcode.
Runningthecodenowshouldgiveyousomethinglikethis:

SettingaTransparentColor
Sincemostofourspriteswon'tbeperfectsquares,weneedsomewaytomakepartsof
themtransparent.Acommonwaytodothisistodecideonacolorthatshouldneverbe
drawn.Thiscolorisnormallysomethingyou'dneveruseinagame,likemagenta(255,0,
255).
WedefinethiscolortobetransparentwithacalltoSDL_SetColorKey().Thisisdone
likeso:
SDL_SetColorKey(surface, SDL_SRCCOLORKEY, SDL_MapRGB(surface->format,
255, 0, 255) );
Thefirstparameterisapointertothesurfacethatcontainsthecolorwe'resettingtobe
transparent.Thisallowsustosetdifferenttransparentcolorsondifferentsurfaces,ifwe
reallywanttodothat.
Thesecondparameterisaflag.Passingit SDL_SRCCOLORKEY specifiesthatwewant
whatwepassasthethirdparametertobethetransparentcolor.
Thethirdparameteristhecoloritself.Thecolorneedstobepassedto
SDL_SetColorKey()inthesurface'sformat.WecallSDL_MapRGB() togetthis.
SDL_MapRGB()takesapixelformataswellastheRGBvaluesofthecolorwewant.You
cangetthepixelformatfromthesurface.It'sstoredintheformatvariable.
Ifyoudon'tunderstandsomeofthisstuff,don'tworry.Ifyouendupdoingmore
advancedthingswithSDL,itmightmatter,butforcurrentpurposesyoujustneedtoset
atransparentcolor.Doingsoisquiteeasy(itonlytakesoneline!).
Inthecodeabove,addthefollowinglineimmediatelyafterthebitmapsurfaceiscreated:
SDL_SetColorKey( bitmap, SDL_SRCCOLORKEY, SDL_MapRGB(bitmap->format,
255, 0, 255) );
Runningthecodenowshouldgiveyouthis:

ClearingtheScreen
Atthemoment,there'snoproblemwiththewaywe'redrawingthings.We'llruninto
problemswhenwestartmovingthingsaroundthough.Theproblemisthatwearen't
clearingthescreenbeforewestartdrawing.Ifsomethingmoves,itwillstillgetdrawnat
itspreviouslocation.
Toclearthescreen,weuseSDL_FillRect(),whichtakesthreeparameters.Thefirst
parameterisapointertoanSDL_Surface.Thissurfacewillbeclearedtoagivencolor.
Toclearthescreen,wepassinthescreenbuffer.
Thesecondparameterisan SDL_Rect storingtheareaofthesurfacethatwewant
cleared.PassinginNULL willcleartheentiresurface.
Thethirdparameteristhecolorwewanttoclearthesurfaceto.Thisworksjustlikeit
didwithSDL_SetColorKey().
Thefollowinglineofcodewillclearthescreentoblack.Itshouldbeplacedbeforeany
otherdrawingcode.
SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0));

Exercises
Ex1)TheonlythingIfindcumbersomeaboutdrawingspriteswithSDListhatyouhave
tofilltwoSDL_Rectstructureseverytime.Thisisofcourseeasilyfixedbywritinga
functionthatdoesitforyou.Trywritingsuchafunctionnow,anddon'tfeelbadifyou
havetolookbacktorememberanSDLfunctionnameoritsparameters.Knowinghowto
useSDLismuchmoreusefulthanmemorizingit.
Here'sanexampleofafunctionthatdrawsasprite:
void drawSprite(SDL_Surface* imageSurface,
SDL_Surface* screenSurface,
int srcX, int srcY,
int dstX, int dstY,
int width, int height)
{
SDL_Rect srcRect;
srcRect.x = srcX;
srcRect.y = srcY;
srcRect.w = width;
srcRect.h = height;
SDL_Rect dstRect;
dstRect.x = dstX;
dstRect.y = dstY;
dstRect.w = width;
dstRect.h = height;
SDL_BlitSurface(imageSurface, &srcRect, screenSurface, &dstRect);
}
CopyrightAaronCox20042005,AllRightsReserved.

You might also like