-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollisionObject.cpp
71 lines (63 loc) · 2.75 KB
/
collisionObject.cpp
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 <iostream>
#include <algorithm> // for min and max
#include "collisionObject.hpp"
CollisionObject::CollisionObject(float x, float y, const sf::Texture &tex) : pos(x, y), visual(tex), vel(0, 0), sz(tex.GetWidth(), tex.GetHeight()) {
updateVisual();
}
void CollisionObject::update(float dt) {
pos += vel * dt;
updateVisual();
}
void CollisionObject::updateVisual() {
visual.SetPosition(pos.x, pos.y);
visual.SetScale(1, 1);
}
void CollisionObject::rotate(float angle) {
angle *= -1;
visual.SetOrigin(0, 0);
visual.SetRotation(angle);
visual.SetOrigin( // make it seem as if rotating around the centre of the object
sz.x/2 - (sqrt(2))*(sz.x/2)*sin((angle+45)*2*M_PI/360.0),
sz.y/2 - (sqrt(2))*(sz.y/2)*cos((angle+45)*2*M_PI/360.0)
);
}
float CollisionObject::testX(const CollisionObject &o) const {
// Compute the intersection boundaries
float left = std::max(pos.x, o.pos.x);
float top = std::max(pos.y, o.pos.y);
float right = std::min(pos.x + sz.x, o.pos.x + o.sz.x);
float bottom = std::min(pos.y + sz.y, o.pos.y + o.sz.y);
if ((left < right) && (top < bottom)) { // If the intersection is valid (positive non zero area), then there is an intersection
if (o.vel.x < 0) return (pos.x + sz.x) - o.pos.x; // if moving left, push right
else if (o.vel.x > 0) return (pos.x-o.sz.x) - o.pos.x; // if moving right, push left
else { // if not moving at all, PANIC!?
std::cout << "Collision panic X" << std::endl;
return -0.1;
}
}
else return 0;
}
float CollisionObject::testY(const CollisionObject &o) const {
// Compute the intersection boundaries
float left = std::max(pos.x, o.pos.x);
float top = std::max(pos.y, o.pos.y);
float right = std::min(pos.x + sz.x, o.pos.x + o.sz.x);
float bottom = std::min(pos.y + sz.y, o.pos.y + o.sz.y);
if ((left < right) && (top < bottom)) { // If the intersection is valid (positive non zero area), then there is an intersection
if (o.vel.y < 0) return (pos.y + sz.y) - o.pos.y; // if moving left, push right
else if (o.vel.y > 0) return (pos.y-o.sz.y) - o.pos.y; // if moving right, push left
else { // if not moving at all, PANIC!?
std::cout << "Collision panic Y" << std::endl;
return -0.1;
}
}
else return 0;
}
bool CollisionObject::collidesWith(const CollisionObject &o) const {
// Compute the intersection boundaries
float left = std::max(pos.x, o.pos.x);
float top = std::max(pos.y, o.pos.y);
float right = std::min(pos.x + sz.x, o.pos.x + o.sz.x);
float bottom = std::min(pos.y + sz.y, o.pos.y + o.sz.y);
return ((left < right) && (top < bottom)); // If the intersection is valid (positive non zero area), then there is an intersection
}