summary refs log tree commit diff stats
path: root/src/camera_system.cpp
blob: 0ef3c36e82264958733349cfce07f3c8bb041564 (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
#include "camera_system.h"
#include "sprite.h"
#include "game.h"
#include "map.h"

void CameraSystem::tick(double dt) {
  if (game_.isGameplayPaused()) return;

  if (!locked_ && followingSprite_ != -1) {
    const Sprite& follow = game_.getSprite(followingSprite_);

    pos_ = calculatePosWithCenter(follow.loc - vec2i{0, 16});
  }

  if (panning_) {
    panThus_ += dt;

    if (panThus_ >= panLength_) {
      panning_ = false;
      pos_ = panEnd_;
    } else {
      pos_.x() = static_cast<double>((panEnd_ - panStart_).x()) / panLength_ * panThus_ + panStart_.x();
      pos_.y() = static_cast<double>((panEnd_ - panStart_).y()) / panLength_ * panThus_ + panStart_.y();
    }
  }
}

void CameraSystem::panToSprite(int targetId, int length) {
  locked_ = true;

  const Sprite& target = game_.getSprite(targetId);

  if (length > 0) {
    panning_ = true;
    panStart_ = pos_;
    panEnd_ = calculatePosWithCenter(target.loc - vec2i{0, 16});
    panLength_ = length;
    panThus_ = 0.0;
  } else {
    pos_ = calculatePosWithCenter(target.loc - vec2i{0, 16});
  }
}

void CameraSystem::destroySprite(int spriteId) {
  if (followingSprite_ == spriteId) {
    followingSprite_ = -1;
  }
}

vec2i CameraSystem::calculatePosWithCenter(vec2i center) const {
  const Map& map = game_.getMap();
  vec2i mapBounds = map.getMapSize() * map.getTileSize();

  vec2i result = center - (fov_ / 2);

  if (result.x() < 0) {
    result.x() = 0;
  }
  if (result.y() < 0) {
    result.y() = 0;
  }
  if (result.x() + fov_.w() >= mapBounds.w()) {
    result.x() = mapBounds.w() - fov_.w() - 1;
  }
  if (result.y() + fov_.h() >= mapBounds.h()) {
    result.y() = mapBounds.h() - fov_.h() - 1;
  }

  return result;
}