summary refs log tree commit diff stats
path: root/src/collision.cpp
blob: b747a9084e0068aeee654e2f0477c2240fb8a399 (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
#include "collision.h"

bool Collision::operator<(const Collision& other) const
{
  // Most important is the type of collision
  if (type_ != other.type_)
  {
    return (static_cast<int>(type_) > static_cast<int>(other.type_));
  }

  // Next, categorize the collisions arbitrarily based on direction
  if (dir_ != other.dir_)
  {
    return (static_cast<int>(dir_) < static_cast<int>(other.dir_));
  }

  // We want to process closer collisions first
  if (axis_ != other.axis_)
  {
    switch (dir_)
    {
      case Direction::left:
      case Direction::up:
      {
        return (axis_ < other.axis_);
      }

      case Direction::right:
      case Direction::down:
      {
        return (axis_ > other.axis_);
      }
    }
  }

  // Order the remaining attributes arbitrarily
  return std::tie(collider_, lower_, upper_) <
    std::tie(other.collider_, other.lower_, other.upper_);
}

bool Collision::isColliding(
  double x,
  double y,
  int w,
  int h) const
{
  int right = x + w;
  int bottom = y + h;

  switch (dir_)
  {
    case Direction::left:
    case Direction::right:
    {
      if (!((bottom > lower_) && (y < upper_)))
      {
        return false;
      }

      break;
    }

    case Direction::up:
    case Direction::down:
    {
      if (!((right > lower_) && (x < upper_)))
      {
        return false;
      }

      break;
    }
  }

  switch (dir_)
  {
    case Direction::left:
    {
      return (axis_ >= x);
    }

    case Direction::right:
    {
      return (axis_ <= right);
    }

    case Direction::up:
    {
      return (axis_ >= y);
    }

    case Direction::down:
    {
      return (axis_ <= bottom);
    }
  }
}