Animating sprites in sfml from a sprite sheet

后端 未结 1 1480
栀梦
栀梦 2021-01-26 12:44

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

相关标签:
1条回答
  • 2021-01-26 13:18

    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 = &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);
    
    0 讨论(0)
提交回复
热议问题