summary refs log tree commit diff stats
path: root/src/systems/animating.cpp
blob: 50a32fcfafa6799537c013a7479171afd5a0e863 (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#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);

    if (sprite.active)
    {
      if (!sprite.frozen)
      {
        sprite.countdown++;
      }

      const Animation& anim = sprite.getAnimation();
      if (sprite.countdown >= anim.getDelay())
      {
        sprite.frame++;
        sprite.countdown = 0;

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

      if (sprite.flickering)
      {
        sprite.flickerTimer = (sprite.flickerTimer + 1) % 6;
      }
    }
  }
}

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);

    if (sprite.active)
    {
      auto& transform = game_.getEntityManager().
        getComponent<TransformableComponent>(entity);

      double alpha = 1.0;
      if (sprite.flickering && (sprite.flickerTimer < 3))
      {
        alpha = 0.0;
      }

      Rectangle dstrect {
        static_cast<int>(transform.pos.x()),
        static_cast<int>(transform.pos.y()),
        transform.size.w(),
        transform.size.h()};

      const AnimationSet& aset = sprite.animationSet;
      game_.getRenderer().blit(
        aset.getTexture(),
        texture,
        aset.getFrameRect(sprite.frame),
        dstrect,
        alpha);
    }
  }
}

void AnimatingSystem::initPrototype(id_type entity)
{
  auto& sprite = game_.getEntityManager().
    getComponent<AnimatableComponent>(entity);

  startAnimation(entity, sprite.origAnimation);

  sprite.countdown = 0;
  sprite.flickering = false;
  sprite.flickerTimer = 0;
  sprite.frozen = false;
}

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

  sprite.animation = std::move(animation);
  sprite.frame = sprite.getAnimation().getFirstFrame();
}