I' creating a simple game, using game states.
I have a gameLoop()
method that calls a running()
method, which contains the switching states, which works correctly.
This is the gameLoop()
method:
void Game::gameLoop()
{
while (window.isOpen()) {
Event event;
while (window.pollEvent(event)) {
if (event.type == Event::Closed){
window.close();
}
}
if (Keyboard::isKeyPressed(Keyboard::Escape)) {
window.close();
}
window.clear();
running(); //this calls the states
window.display();
}
running()
method calls all the states:
void Game::running()
{
switch (state)
{
//other cases here
case s_play:
play();
break;
default:
break;
}
}
And the play()
method draws the sprite and moves it:
void Game::play()
{
Texture myTexture; //I've also tried to declare these outside the method
Sprite mySprite;
///////////Graphics
myTexture.loadFromFile("res/img/player.png");
mySprite.setTexture(myTexture);
//////////Movement
static sf::Clock clock;
float dt = clock.restart().asSeconds();
Vector2f move;
if (Keyboard::isKeyPressed(Keyboard::A))
{
move.x--;
}
std::cout << mySprite.getPosition().x << "\n";
}
if (Keyboard::isKeyPressed(Keyboard::D))
{
move.x++;
}
std::cout << mySprite.getPosition().x << "\n";
}
mySprite.move(move*300.0f*dt);
window.draw(mySprite);
}
The problem is that the sprite just moves on the spot, and the output obtained from the std::cout is the following, when pressing A or D:
The function of the movement works, because it was tested elsewhere. I think that I'm updating correctly or initializing something in the wrong way, but I can't figure it out.
Game
class instead? – Some programmer dudesf::Clock::restart()
returns the elapsed time and then restarts it @Someprogrammerdude. The clock is static, so that shouldn't make a difference – Arnav Borborah