#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <string>
#include <iostream>
int main()
{
enum Direction { Down, Left, Right, Up };
sf::Vector2i screenDimensions(800,600);
sf::RenderWindow window(sf::VideoMode(screenDimensions.x, screenDimensions.y), "SFML Game");
int animationCounter = 0, animationFrameDuration = 300;
sf::Texture pTexture;
sf::Sprite playerImage;
sf::Clock clock;
sf::Font font;
sf::Music music;
sf::Vector2i source(1, Down);
{
if(!music.openFromFile("KingOfTheDesert.ogg"))
std::cout << "Error: Could not locate music file." << std::endl;
}
{
if(!font.loadFromFile("Gabriola.ttf"))
std::cout << "Error: Could not locate the font file." << std::endl;
}
{
if(!pTexture.loadFromFile("Player.png"))
std::cout << "Error: Could not load player image." << std::endl;
else
playerImage.setTexture(pTexture);
}
clock.restart();
while (window.isOpen())
{
sf::Event Event;
while (window.pollEvent(Event))
{
switch(Event.type)
{
case sf::Event::Closed:
window.close();
case sf::Event::KeyPressed:
if(Event.key.code == sf::Keyboard::Up)
source.y = Direction::Up;
else if(Event.key.code == sf::Keyboard::Down)
source.y = Direction::Down;
else if(Event.key.code == sf::Keyboard::Left)
source.y = Direction::Left;
else if(Event.key.code == sf::Keyboard::Right)
source.y = Direction::Right;
if(Event.key.code == sf::Keyboard::P)
music.play();
if(Event.key.code == sf::Keyboard::Escape)
window.close();
}
if(source.x * 32 >= pTexture.getSize().x)
source.x = 0;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
source.y = Up;
playerImage.move(0, -1);
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
source.y = Down;
playerImage.move(0, 1);
}animationCounter
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
source.y = Right;
playerImage.move(1, 0);
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
source.y = Left;
playerImage.move(-1, 0);
}
if(source.x * 32 >= pTexture.getSize().x)
source.x = 0;
animationCounter += clock.restart().asMilliseconds();
if(animationCounter >= animationFrameDuration)
{
animationCounter -= animationFrameDuration;
source.x++;
if(source.x * 32 >= pTexture.getSize().x)
source.x = 0;
}
playerImage.setTextureRect(sf::IntRect(source.x * 32, source.y * 32, 32, 32));
window.clear();
window.draw(playerImage);
window.display();
}
return 0;
}
Well I would do something like that, sometimes I replace the if(animationCounter >= animationFrameDuration) by a while so that when we have a very very long frame it doesn't influence the overall animation in a long time perspective (although if you have frames that long this might not be your first concern ^^).
Can't compile it myself so don't hesitate if something is not right