summaryrefslogtreecommitdiff
path: root/src/graphics/animation.cpp
blob: 828772cb737f533585bf17249d1c2af443ef20e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include "animation.h"

#include <string>

namespace Graphics{

    Animation::Animation(){}

    Animation::Animation(const sf::Texture& texture, std::size_t count,
            sf::Time duration, bool repeat)
        : numFrames_ (count)
        , currentFrame_(0)
        , duration_(duration)
        , elapsedTime_(sf::Time::Zero)
        , repeat_ (repeat)
    {
        sprite_.setTexture(texture);
        sf::Vector2u size = texture.getSize();

        if (size.x % numFrames_ != 0){
            throw ("Animation: size not divisible by " + std::to_string(count));
        }
        frameSize_.x = static_cast<std::size_t>(size.x / count);
        frameSize_.y = size.y;

        sprite_.setTextureRect( sf::IntRect(0,0,frameSize_.x,frameSize_.y) );
    }

    void Animation::update(sf::Time deltaTime){
        sf::Time timePerFrame = duration_ / static_cast<float>(numFrames_);
        elapsedTime_ += deltaTime;


        while (elapsedTime_ > timePerFrame ){

            if(currentFrame_ == numFrames_ - 1){
                if (repeat_) {
                    currentFrame_ = 0;
                } else {
                    return;
                }
            } else {
                currentFrame_ ++;
            }
            elapsedTime_ -= timePerFrame;
            sprite_.setTextureRect(
                    sf::IntRect(
                        currentFrame_ * frameSize_.x,
                        0,
                        frameSize_.x,
                        frameSize_.y)
            );
        }
    }

    void Animation::draw(sf::RenderTarget& target, sf::RenderStates states)
        const{
        target.draw(sprite_, states);
    }
    void Animation::reset(){
        currentFrame_ = 0;
        elapsedTime_ = sf::Time::Zero;
        sprite_.setTextureRect( sf::IntRect(0,0,frameSize_.x,frameSize_.y) );
    }

    bool Animation::finished() const{
        return (!repeat_ && currentFrame_ == numFrames_ - 1) ;
    }
}