#include #include #include #include using namespace std; using namespace sf; class AnimatedSprite : public Sprite { private: Texture texture; vectorframes_; float current_frame_time_ = 0.0; int current_frame_index_ = 0; float fps_ = 4.0; float v_x = 0.0; float v_y = 0.0; float acc_x = 0.0; float acc_y = 50.0; public: AnimatedSprite(Vector2f position) { texture.loadFromFile("character.png"); setTexture(texture); setPosition(position); setScale(4,4); } void add_animation_frame(IntRect frame) { if(frames_.empty()) { setTextureRect(frame); } frames_.push_back(frame); } void step(float delta_t) { v_x += delta_t*acc_x; v_y += delta_t*acc_y; current_frame_time_ +=delta_t; cerr<= (1.0/fps_)) { current_frame_time_ -= (1.0/fps_); current_frame_index_ = (current_frame_index_ +1) % frames_.size(); setTextureRect(frames_[current_frame_index_]); } if(Keyboard::isKeyPressed(Keyboard::W)) { move(0,-v_y*delta_t); // add_animation_frame(IntRect(0, 0, 32, 32)); } if(Keyboard::isKeyPressed(Keyboard::S)) { move(0,v_y*delta_t); // add_animation_frame(IntRect(0, 0, 32, 32)); } if(Keyboard::isKeyPressed(Keyboard::A)) { move(-v_x*delta_t,0); // add_animation_frame(IntRect(0, 0, 32, 32)); } if(Keyboard::isKeyPressed(Keyboard::D)) { move(v_x*delta_t,0); // add_animation_frame(IntRect(0, 0, 32, 32)); } } }; int main() { // create the window sf::RenderWindow window(sf::VideoMode(800, 600), "My window"); AnimatedSprite hero(Vector2f(600,100)); hero.add_animation_frame({0,0,50,37}); hero.add_animation_frame({50,0,50,37}); hero.add_animation_frame({100,0,50,37}); Clock clock; // run the program as long as the window is open while (window.isOpen()) { float delta_t = float (clock.getElapsedTime().asMicroseconds())/1000000.0; clock.restart(); // check all the window's events that were triggered since the last iteration of the loop sf::Event event; while (window.pollEvent(event)) { // "close requested" event: we close the window if (event.type == sf::Event::Closed) window.close(); } hero.step(delta_t); // clear the window with black color window.clear(sf::Color::Black); window.draw(hero); // draw everything here... // end the current frame window.display(); } return 0; }