In this post, we are going to learn about how to animate using sprite sheets. It is very easy and simple to do with SDL2. You should check out the previous post where we rendered out first image. If you feel like
SDL_Rect are easy, animating using sprite sheet is not a problem at all.
What is a sprite sheet? It is just a bundle of sprites packed into one image. This is a much better and optimized approach. It will be a mess to have an individual image for each sprite. A sprite sheet looks like this:
We will be using the sprite sheet given above. So, just download it. My codes below will only run fine for a sprite sheet having 8 frames in a single row.
Animation is the process of drawing similar images in a sequence to simulate some action like walking. Usually, we use the word, 'frame' for each sprite being rendered in an animation. Sprite sheets are very commonly used for animation in 2D. Every animation done using sprite sheet, needs two things:
Our sprite sheet contains 8 frames. Therefore, we already fulfilled the first need. The second need can be fulfilled by doing some calculations with time. This is very easy to do with SDL.
SDL provides us its own timer. It starts to count the time in milliseconds when the SDL is initialized. We can get that time in milliseconds using the method:
Now that we know SDL timer, we need to know that it requires two rectangles to completely describe an image on the screen.
The first one is the one we already know. But the second one is the one which acts as a texture. We need to tell SDL which part of texture is to be rendered on the screen which is possible through Texture Rectangle. If we don't tell that to SDL, SDL will render the whole texture and fit it to the window rectangle (the first rectangle that we discussed in the previous post).
The mystery of third parameter in
SDL_RenderCopy() lies here. That parameter is for texture rectangle.
That's all we need to know. The only thing that we haven't discussed yet, is a method for getting texture width and height. It is called
SDL_QueryTexture(). Make sure to use the above sprite sheet or else it will not work fine for you!
The concept behind these codes is just the same as what we are getting through in the paragraphs above and in the previous posts. If you still don't get the concept of texture rectangle, you can just have this:
textureRect.x = SDL_GetTicks() / 100;. Then, you will see that, with time, the texture is gradually proceeding to the right end. Similarly, you can do that with y-position, width or height. In the above codes, we are just shifting the position of texture rectangle to the position of individual frame with proper and regular delays.
All the other code is as clear and self-explanatory as it looks! And if it is not, you must go through all my previous posts of this series. For having more programming stuff or if you have something to discuss with me, you can visit my blog: bacprogramming.wordpress.com
And as always, Happy Coding!