Animate a sprite
You want to control the animation of an object: faster, stopped on a frame, or doing something when it ends.
The speed lives in the sprite
Section titled “The speed lives in the sprite”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.
In the code: animSpeed multiplies
Section titled “In the code: animSpeed multiplies”#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);How it works
Section titled “How it works”- If the sprite has an fps,
animSpeedis a multiplier:1(the default) uses the speed of the sprite,2is double,0.5is half and0stops the animation. - If the sprite has no fps,
animSpeedcounts in frames per step:1changes frame every step (60 per second),0.25every 4 steps (15 per second). That’s how it is in the tutorial, which doesn’t set an fps on the sprites. frameis the current frame, starting at 0. You can read it and change it.onAnimationEndis called when the animation completes a loop.
Variations
Section titled “Variations”Stop on a frame:
animSpeed = 0;frame = 1; // second frameSwitch 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 horizontallyangle = 45; // rotated 45 degrees (only the drawing, not the collision)