summary refs log tree commit diff stats
path: root/src/systems/animating.cpp
blob: 22224c9ff41c4aab154e470dff4de991673d78f8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include "animating.h"
#include "game.h"
#include "components/animatable.h"
#include "components/transformable.h"

void AnimatingSystem::tick(double)
{
  std::set<id_type> spriteEntities =
    game_.getEntityManager().getEntitiesWithComponents<AnimatableComponent>();

  for (id_type entity : spriteEntities)
  {
    auto& sprite = game_.getEntityManager().
      getComponent<AnimatableComponent>(entity);

    sprite.setCountdown(sprite.getCountdown() + 1);

    const Animation& anim = sprite.getAnimation();
    if (sprite.getCountdown() >= anim.getDelay())
    {
      sprite.setFrame(sprite.getFrame() + 1);
      sprite.setCountdown(0);

      if (sprite.getFrame() >= anim.getFirstFrame() + anim.getNumFrames())
      {
        sprite.setFrame(anim.getFirstFrame());
      }
    }
  }
}

void AnimatingSystem::render(Texture& texture)
{
  std::set<id_type> spriteEntities =
    game_.getEntityManager().getEntitiesWithComponents<
      AnimatableComponent,
      TransformableComponent>();

  for (id_type entity : spriteEntities)
  {
    auto& sprite = game_.getEntityManager().
      getComponent<AnimatableComponent>(entity);

    auto& transform = game_.getEntityManager().
      getComponent<TransformableComponent>(entity);

    Rectangle dstrect {
      static_cast<int>(transform.getX()),
      static_cast<int>(transform.getY()),
      transform.getW(),
      transform.getH()};

    const AnimationSet& aset = sprite.getAnimationSet();
    game_.getRenderer().blit(
      aset.getTexture(),
      texture,
      aset.getFrameRect(sprite.getFrame()),
      dstrect);
  }
}

void AnimatingSystem::startAnimation(id_type entity, std::string animation)
{
  auto& sprite = game_.getEntityManager().
    getComponent<AnimatableComponent>(entity);

  sprite.setAnimation(animation);
  sprite.setFrame(sprite.getAnimation().getFirstFrame());
}