Skip to content
Download

Animate a sprite

You want to control the animation of an object: faster, stopped on a frame, or doing something when it ends.

Slice the image into frames in the sprite editor and, on the timeline, set the fps: how many frames per second the animation has. For example, 12 for a fast explosion or 4 for a slow flame. The Prévia (preview) shows the animation at that speed.

With the fps set, every object that uses that sprite already animates at the right speed, without a single line of code.

#include <brasa/brasa.hpp>
using namespace brasa;
class Explosion : public Entity {
public:
void onSpawn() override {
animSpeed = 2; // twice as fast as the sprite's fps
}
void onAnimationEnd() override {
destroy(); // the explosion is over: disappear
}
};
BRASA_ENTITY(Explosion);
  • If the sprite has an fps, animSpeed is a multiplier: 1 (the default) uses the speed of the sprite, 2 is double, 0.5 is half and 0 stops the animation.
  • If the sprite has no fps, animSpeed counts in frames per step: 1 changes frame every step (60 per second), 0.25 every 4 steps (15 per second). That’s how it is in the tutorial, which doesn’t set an fps on the sprites.
  • frame is the current frame, starting at 0. You can read it and change it.
  • onAnimationEnd is called when the animation completes a loop.

Stop on a frame:

animSpeed = 0;
frame = 1; // second frame

Switch sprites, for example between standing (player_parado) and walking (player_andando). When you switch, the animation goes back to frame 0 by itself:

sprite = (hspeed != 0) ? "player_andando" : "player_parado";

Flip the sprite to the other side and rotate it:

scaleX = -1; // flipped horizontally
angle = 45; // rotated 45 degrees (only the drawing, not the collision)