Search code examples
c++sfml

I don't see the animation of the sprite


This is code after includes:

Sprite player;
Texture playerTexture;
IntRect playerContainer(0, 0, 32, 32);
Vector2f playerPosition;

int playerDirection = 0; // 0 - fwd, 1 - back, 2 - stay

This is animation update method:

void updateAnims(Clock clock, float time) {
  if(time > 0.3f) {
    if(playerDirection == 0) playerContainer.top = 0;
    else if(playerDirection == 1) playerContainer.top = 32;
    else if(playerDirection == 2) playerContainer.top = 64;

    if(playerContainer.left == 96) playerContainer.left = 0;
    else playerContainer.left += 32;

    player.setTextureRect(playerContainer);
    clock.restart();
  }
}

and this method is updated in "int main()" method.

int main() {
  // Init window
  RenderWindow window(VideoMode(800, 600), "RPG");
  Clock gameClock;
  Clock animClock;
  float gameTime;
  float animTime;

  // Setting up the player
  playerTexture.loadFromFile("player.png");
  player.setTexture(playerTexture);
  player.setTextureRect(playerContainer);
  player.setScale(Vector2f(3.f, 3.f));
  playerPosition.x = 30;
  playerPosition.y = 120;
  player.setPosition(playerPosition);

  while(window.isOpen()) {
    Event event;
    while(window.pollEvent(event)) {
      if(event.type == Event::Closed) {
        window.close();
      }
    }

    checkInputs(gameTime);

    animTime = animClock.getElapsedTime().asSeconds();
    updateAnims(animClock, animTime);

    window.clear();

    gameTime = gameClock.getElapsedTime().asMilliseconds();
    gameClock.restart();

    window.display();
  }

  return 0;
}

Turns out that sprite is created in main method, gets texture and texture shape, gets position, but not drawn. Why?

I think think the problem is in animation method but I tried different variations of solutions.


Solution

  • You should call window.draw(player) method between window.clear() and window.display() to actually draw player sprite on screen.