This is part of a series of small projects and tutorials using C++ and SFML
Library version: SFML 3.0.0
C++ Standard: ISO C++20
My Base Project: https://github.com/l-paz91/SFMLProjects/blob/main/main.cpp
In this project, we'll make a simple app that loads a texture (image), gives that texture to a sprite and animates it. Here's what the finished product will look like:
Step 1 - Creating a Sprite
What is a sprite? In game development it usually refers to a drawable object that references a texture. They usually have functions that allow you to set the position, rotation, scale and others. They are used primarily for the main "objects" in your games like the main character, enemies, items etc.
By themselves, sprites have no concept of animation. They load a single image each frame. Therefore to animate them, you need some code that updates the image each frame.
Why doesn't SFML do this for you? Well, animations come in all shapes, sizes and varieties. The speed, duration, loop ability. These are all left down to the programmer to implement as the developers of the libraries cannot be expected to cater to every situation.
Enough talking though. Let's make a sprite and show it on the screen. Sprites load textures. So we'll need a texture first and give a reference of it to the Sprite.
I'll be using the following spritesheet for the purposes of this tutorial:
Please note this is for learning purposes only.
The reason I'm using it is because all the separate frames we need are nicely laid out into little squares so we can easily access them from our texture when we need to update the animation each frame.
Step 2 - Offsetting into a Texture
Now this doesn't work as expected because we're just loading the entire image and displaying that. We only want to display part of the texture. So we'll need to create an offset into it. I've already done some calculations for you and those squares are 48x48 pixels. The start of the walk animation is at x268, y576.
That's better.
Step 3 - Animating the Frames
So to animate this, all we have to do is move the texture rect 48 pixels to the right (+ a 4 pixel gap between frames) to give us the next frame. Then we do the same again, then go backwards to the start. We can simulate this by just using a vector to store the positions.
And done! And that's how you basically animate sprites. We use the delta time to gives us a nice animation speed as well. Animation is a massive part of game development and it would be nice if we could wrap up of our animating code into something reusable.
No comments:
Post a Comment