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
|
class Animation
{
private:
std::string name;
std::vector<sf::IntRect> frames;
sf::Clock clock;
sf::Time frame_length;
size_t current_frame;
bool is_playing;
public:
Animation(std::string n, sf::Time fl): name(n), frame_length(fl), current_frame(0), is_playing(0) {}
void AddFrame(int sx, int sy, int fx, int fy) { frames.push_back(sf::IntRect(sx,sy,fx,fy)); }
void Update()
{
if(!is_playing) return;
if(clock.getElapsedTime() < frame_length) return;
if(current_frame+1 >= frames.size()) current_frame = 0;
else current_frame++;
clock.restart();
}
sf::IntRect& GetCurrentFrame() { return frames[current_frame]; }
void Start()
{
if(!is_playing)
{
is_playing = true; clock.restart();
}
}
void Stop() { if(is_playing) is_playing = false; current_frame = 0; }
const bool IsPlaying() { return is_playing; }
};
// IN MAIN
...
// Attempting to get the first strip of frames
// The PNG size is 128x192 with 16 images
// I have deduced that each image is 32x48
Animation animation("walking_south",sf::milliseconds(250));
for(unsigned int x = 0; x < texture_handler.GetTexture(0).getSize().x; x+=32)
animation.AddFrame(x,0,x+31,47);
// Create drawable sprite
sf::Sprite sprite(texture_handler.GetTexture(0),animation.GetCurrentFrame());
sprite.setOrigin(sprite.getOrigin().x+16,sprite.getOrigin().y+24);
sprite.setPosition(sf::Vector2f(0,0));
...
// Update section
animation.Update();
sprite.setTextureRect(animation.GetCurrentFrame());
std::cout << sprite.getTextureRect().left << " "
<< sprite.getTextureRect().top << " "
<< sprite.getTextureRect().width << " "
<< sprite.getTextureRect().height << "\n";
// Graphics rendering
window.clear(sf::Color::White);
window.draw(sprite);
window.display();
|