I'm new to SFML and I'm wondering how I'd do this.
Right now I have a sprite (spritesheet) which animatesusing IntRect correctly depending on which direction button you press. The character moves in that direction too. However, I have no limit on the animation, so it's incredibly fast. I tried adding sf::sleep which made the sprite animate at a nice speed, but this stopped my character's movement. So one or the other is broken right now, whether I use sleep or not.
My eventual goal is to make Pokémon movement:
- Press right, control is taken from the player
- the sprite moves right one grid space (say 14.f)
- one animation cycle happens during this movement
- the movement takes .5f seconds to elapse
I have no idea how to do this. I'm guessing something either to do with the Clock class or threading the animation and movement separately.
Thanks in advance for you help (:
// Game Loop:
while(Screen.isOpen())
{
// Check if the window is closed:
sf::Event event;
while(Screen.pollEvent(event))
{
if(event.type == sf::Event::Closed || sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
Screen.close();
}
// Set drawing positions and velocities:
// - Left and Right:
if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
src.y = sL;
vel.x = -moveSpeed;
} else if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
src.y = sR;
vel.x = moveSpeed;
} else {
vel.x = 0;
}
// - Up and Down:
if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
src.y = sU;
vel.y = -moveSpeed;
} else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
src.y = sD;
vel.y = moveSpeed;
} else {
vel.y = 0;
}
// Move the player:
pos.x += vel.x;
pos.y += vel.y;
// Animate image:
if(vel.x != 0 || vel.y != 0) {
src.x += spritesheet.getSize().x / 4;
// - No limit in here..
} else {
src.x = 0;
}
// - reset to the first frame:
if(src.x == spritesheet.getSize().x)
src.x = 0;
// Refresh the screen:
Screen.clear();
// Draw and display the player:
player.setTextureRect(sf::IntRect(src.x, src.y, spritesheet.getSize().x / 4, spritesheet.getSize().y / 4));
player.setPosition(pos.x, pos.y);
Screen.draw(player);
// Show the screen:
Screen.display();
}