Game dev, Suit’em up – SpriteManager with animated sprites
|
We created an early SpriteManager in the start of the project but it couldn’t load animated sprites or load sprites from a part in a spritesheet. I have now added this functionality. I started with creating a wrapper around sf::Sprite and I have created the AnimatedSprite class. I’m not really that proud of the wrapper since I put a lot of virtual functions in there that are only used by AnimatedSprite. After adding the sprite types I added methods in the SpriteManager for loading animated sprites using .txt-files, just as we have learned to do in our first programming course. Here is an example of such a file: And here is the code for loading it: There is another function for adding more frames, it’s a bit shorter and looks like this: Much of the code in these to methods (LoadAnimation() and AddAnimation()) are written twice and I should put this together. I will probably do this in the future but right now there are more pressing matters to attend to in the project. A frame is a struct within the AnimatedSprite class. It holds these variables: x position, y position, width, height, timer. The timer counts down when the sprites Update(float p_fDeltaTime) method is called and when it reaches zero the animated sprite changes frame. The timer is reduced with deltatime, like so: timer -= deltatime. The SpriteManager is pretty robust right now. It saves Sprite pointers in a std::map and the same goes for sf::Texture pointers. When loading any type of sprite, the sf::Texture map re-uses the same file if it exists in the std::map, otherwise it attempts to load it from file. Loading sprites now takes parameters for location in the spritesheet (texture) and width/height. To set or change this location and width/height the Sprite->setTextureRect(sf::Intrect) function is used. It looks like this: Sprite->setTextureRect(sf::IntRect(p_iPosX, p_iPosY, p_iWidth, p_iHeight)) Next up is setting and changing the animations of a gameobject sprite. This is done by calling the SetAnimation(const std::string &p_sIdentifier) method. So for example, the player avatar “Barney” is supposed to have different sprites making up all parts his body. His legs is one of these parts. When loading the sprite it first uses LoadAnimated() and then a couple of AddAnimation() for each animation type (i.e. Idle_right, Running_left). When the player makes Barney run to the right a check is done, then the animation is changed using the SetAnimation(“running_right”) method. The same principle is used for all times when changing animation, be it the avatar, enemies or what ever. |
