Hello there! I have recently played around with moving characters (with animation) from a single sprite sheet. I want to know whether I have done this correctly or in the most efficient way? (it does work!)
My sprite sheet contained 4 different angles of my character with 3 different positions for each. ( 96 x 128 )
EDIT: I am also having a problem with the speed at which is goes through the animation (not the speed it moves across the screen), is there anyway to control how fast it cycles through the sprite sheet?
Here's my code!
#include <SFML/Graphics.hpp>
#include <string>
#include <iostream>
int main()
{
enum Direction{ Down, Left, Right, Up };
sf::Vector2i source(1, Down);
sf::RenderWindow window(sf::VideoMode(800, 450), "Testing", sf::Style::Fullscreen);
sf::Texture pTexture;
sf::Sprite pChar;
//load sprite sheet
if(!pTexture.loadFromFile("image.png"))
std::cout << "Error" << std::endl;
pChar.setTexture(pTexture);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
source.y = Up;
pChar.move(0, -0.1);
//animation
source.x++;
if(source.x * 32 >= pTexture.getSize().x)
{
source.x = 0;
}
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
source.y = Down;
pChar.move(0, 0.1);
//animation
source.x++;
if(source.x * 32 >= pTexture.getSize().x)
{
source.x = 0;
}
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
source.y = Right;
pChar.move(0.1, 0);
//animation
source.x++;
if(source.x * 32 >= pTexture.getSize().x)
{
source.x = 0;
}
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
source.y = Left;
pChar.move(-0.1, 0);
//animation
source.x++;
if(source.x * 32 >= pTexture.getSize().x)
{
source.x = 0;
}
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
window.create(sf::VideoMode(800, 450), "Testing", sf::Style::Default);
}
pChar.setTextureRect(sf::IntRect(source.x * 32, source.y * 32, 32, 32));
window.draw(pChar);
window.display();
}
return 0;
}
ALSO, when I change the size of my window so does the sprite, how do I give it a fixed size?