I am trying to animate a sprite in sfml. At the moment I am able to move the sprite and change it\'s image when moving in a different direction, but I want to animate it while i
You need to keep track of the frames in the animation (list of sf::IntRects). And have some sort of delay inbetween. On update, simply move through the frames and apply the rectangle.
struct Frame {
sf::IntRect rect;
double duration; // in seconds
};
class Animation {
std::vector<Frame> frames;
double totalLength;
double totalProgress;
sf::Sprite *target;
public:
Animation(sf::Sprite& target) {
this->target = ⌖
totalProgress = 0.0;
}
void addFrame(Frame&& frame) {
frames.push_back(std::move(frame));
totalLength += frame.duration;
}
void update(double elapsed) {
totalProgress += elapsed;
double progress = totalProgress;
for(auto frame : frames) {
progress -= (*frame).duration;
if (progress <= 0.0 || &(*frame) == &frames.back())
{
target->setTextureRect((*frame).rect);
break; // we found our frame
}
}
};
You can use like so:
sf::Sprite myCharacter;
// Load the image...
Animation animation(myCharacter);
animation.addFrame({sf::IntRect(x,y,w,h), 0.1});
// do this for as many frames as you need
// In your main loop:
animation.update(elapsed);
window.draw(myCharacter);