-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollider.cpp
More file actions
90 lines (72 loc) · 2.22 KB
/
collider.cpp
File metadata and controls
90 lines (72 loc) · 2.22 KB
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
#include "collider.h"
Collider::Collider(GameObject* owner) : Component(owner, ComponentType::T_Collider)
{
this->isTrigger = false;
this->layer = CollisionLayer::Default;
this->manifold = Manifold();
}
void Collider::addCollisionLayer(CollisionLayer layer)
{
this->collideLayers.push_back(layer);
}
void Collider::update()
{
this->setPosition();
}
void Collider::setPosition()
{
sf::Vector2f ownerPosition = this->owner->transform->getPosition();
this->rect = sf::FloatRect(ownerPosition.x, ownerPosition.y, this->getRect().width, this->getRect().height);
}
Manifold Collider::intersects(Collider* other)
{
sf::FloatRect rectSelf = this->getRect();
sf::FloatRect rectOther = other->getRect();
if (rectSelf.intersects(rectOther))
{
this->setManifold(true, other);
}
return this->manifold;
}
void Collider::resolveOverlap(Manifold manifold)
{
Transform* transform = this->owner->transform;
if (transform->getStatic())
{
return;
}
sf::FloatRect rectSelf = this->getRect();
sf::FloatRect rectOther = manifold.other->getRect();
std::vector<std::pair<float, std::pair<int, int>>> overlaps = {
{rectOther.left + rectOther.width - rectSelf.left, {1, 0}},
{rectSelf.left + rectSelf.width - rectOther.left, {-1, 0}},
{rectOther.top + rectOther.height - rectSelf.top, {0, 1}},
{rectSelf.top + rectSelf.height - rectOther.top, {0, -1}}
};
float smallestOverlap = std::numeric_limits<float>::infinity();
std::pair<int, int> smallestOverlapDirection = {0, 0};
for (const auto& overlap : overlaps) {
if (overlap.first > 0 && overlap.first < smallestOverlap) {
smallestOverlap = overlap.first;
smallestOverlapDirection = overlap.second;
}
}
if (smallestOverlap != std::numeric_limits<float>::infinity())
{
if (smallestOverlapDirection == std::pair<int, int>(0, 0))
{
// HANDLE GRAVITY RESET HERE
}
transform->move(sf::Vector2f(smallestOverlap * smallestOverlapDirection.first, smallestOverlap * smallestOverlapDirection.second));
}
}
void Collider::setManifold(bool colliding, Collider* other)
{
this->manifold.colliding = colliding;
this->manifold.other = other;
}
void Collider::resetManifold()
{
this->manifold.colliding = false;
this->manifold.other = nullptr;
}