Animations with Sprite Sheets in SDL2
Here's a neat tutorial for elevating your image manipulation to the next level using sprite sheets.
Join the DZone community and get the full member experience.
Join For Freemany of the previous sdl2 tutorials have involved working with images. in this article, we’re going to take this to the next level, using a very simple technique to animate our images and make them feel more alive.
our project setup for this article is just the same as in “ loading images in sdl2 with sdl_image ," and in fact our starting code is adapted from that article:
#include <sdl.h>
#include <sdl_image.h>
int main(int argc, char ** argv)
{
bool quit = false;
sdl_event event;
sdl_init(sdl_init_video);
img_init(img_init_png);
sdl_window * window = sdl_createwindow("sdl2 sprite sheets",
sdl_windowpos_undefined, sdl_windowpos_undefined, 640, 480, 0);
sdl_renderer * renderer = sdl_createrenderer(window, -1, 0);
sdl_surface * image = img_load("spritesheet.png");
sdl_texture * texture = sdl_createtexturefromsurface(renderer, image);
while (!quit)
{
sdl_waitevent(&event);
switch (event.type)
{
case sdl_quit:
quit = true;
break;
}
sdl_rendercopy(renderer, texture, null, null);
sdl_renderpresent(renderer);
}
sdl_destroytexture(texture);
sdl_freesurface(image);
sdl_destroyrenderer(renderer);
sdl_destroywindow(window);
img_quit();
sdl_quit();
return 0;
}
this image is 128 pixels wide and 64 pixels high. it consists of 4 sub-images (called
sprites
or
frames
), each 32 pixels wide. if we can rapidly render each image in quick succession, just like a cartoon, then we have an animation! ��
now, those ugly borders in the image above are just for demonstration purposes. here’s the same image, without borders and with transparency:
if we now try to draw the above on the default black background, we’re not going to see anything, are we? fortunately, it’s easy to change the background colour, and we’ve done it before in “
handling keyboard and mouse events in sdl2
“. just add the following two lines before the
while
loop:
sdl_setrenderdrawcolor(renderer, 168, 230, 255, 255);
sdl_renderclear(renderer);
now we get an early peek at what the output is going to look like. press ctrl+shift+b to build the project, and then copy sdl2.dll , all the sdl_image dlls, and the spritesheet into the debug folder where the executable is generated.
once that is done, hit f5:
so at this point, there are two issues we want to address. first, we don’t want our image to take up the whole window, as it’s doing above. secondly, we only want to draw one sprite at a time. both of these are pretty easy to solve if you remember sdl_rendercopy() ‘s last two parameters: a source rectangle (to draw only a portion of the image) and a destination rectangle (to draw the image only to a portion of the screen).
so let’s add the following at the beginning of the
while
loop:
sdl_rect srcrect = { 0, 0, 32, 64 };
sdl_rect dstrect = { 10, 10, 32, 64 };
…and then update our sdl_rendercopy() call as follows:
sdl_rendercopy(renderer, texture, &srcrect, &dstrect);
note that the syntax we’re using to initialise our
sdl_rect
s is just shorthand to set all of the
x
,
y
,
w
(width) and
h
(height) members all at once.
let’s run the program again and see what it looks like:
okay, so like this we are just rendering the first sprite to a part of the window. now, let’s work on actually animating this. at the beginning of the
while
loop, add the following:
uint32 ticks = sdl_getticks();
sdl_getticks () gives us the number of milliseconds that passed since the program started. thanks to this, we can use the current time when calculating which sprite to use. we can then simply divide by 1000 to convert milliseconds to seconds:
we then divide the seconds by the number of sprites in our spritesheet, in this case 4. using the modulus operator ensures that the sprite number wraps around, so it is never greater than 3 (remember that counting is always zero-based, so our sprites are numbered 0 to 3).
uint32 sprite = seconds % 4;
finally, we replace our
srcrect
declaration by the following:
sdl_rect srcrect = { sprite * 32, 0, 32, 64 };
instead of using an
x
value of zero, as we did before, we’re passing in the
sprite
value (between 0 and 3, based on the current time) multiplied by 32 (the width of a single sprite). so with each second that passes, the sprite will be extracted from the image at x=0, then x=32, then x=64, then x=96, back to x=0, and so on.
let’s run this again:
you’ll notice two problems at this stage. first, the animation is very irregular, in fact it doesn’t animate at all unless you move the mouse or something. second, the sprites seem to be dumped onto one another, as shown by the messy image above.
fortunately, both of these problems can be solved with code we’ve already used in “ handling keyboard and mouse events in sdl2 “. the first issue is because we’re using sdl_waitevent() , so the program doesn’t do anything unless some event occurs. thus, we need to replace our call to sdl_waitevent() with a call to sdl_pollevent() :
while (sdl_pollevent(&event) != null)
{
switch (event.type)
{
case sdl_quit:
quit = true;
break;
}
}
the second problem is because we are drawing sprites without clearing the ones we drew before. all we need to do is add a call to sdl_renderclear() before we call sdl_rendercopy() :
sdl_renderclear(renderer);
great! you can now admire our little character shuffling at one frame per second:
it’s good, but it’s a bit slow. we can make it faster by replacing the animation code before the
srcrect
declaration with the following (10 frames per second):
uint32 ticks = sdl_getticks();
uint32 sprite = (ticks / 100) % 4;
woohoo! �� look at that little guy dance! (the image below is animated, but this seems only to work in firefox.)
so in this article, we learned how to animate simple characters using sprite sheets, which are really just a digital version of a cartoon. we used
sdl_rendercopy()
‘s
srcrect
parameter to draw just a single sprite from the sheet at a time, and selected that sprite using the current time based on
sdl_getticks
().
this is an updated version of “ sdl2: animations with sprite sheets ," originally posted on march 30, 2014 at programmer’s ranch. the source code is available at the gigi labs bitbucket repository .
Published at DZone with permission of Daniel D'agostino, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments