|
| 1 | +#ifndef COLLISION_H |
| 2 | +#define COLLISION_H |
| 3 | + |
| 4 | +#include <cmath> |
| 5 | +#include <algorithm> |
| 6 | + |
| 7 | +#include "Rectangle.h" |
| 8 | +#include "Vector.h" |
| 9 | + |
| 10 | +class Collision { |
| 11 | +public: |
| 12 | + static inline bool is_colliding(Rectangle& a, Rectangle& b, float angleOfA, float angleOfB){ |
| 13 | + Vector A[] = { Vector( a.get_draw_x(), a.get_draw_y() + a.get_height() ), |
| 14 | + Vector( a.get_draw_x() + a.get_width(), a.get_draw_y() + a.get_height() ), |
| 15 | + Vector( a.get_draw_x() + a.get_width(), a.get_draw_y() ), |
| 16 | + Vector( a.get_draw_x(), a.get_draw_y() ) |
| 17 | + }; |
| 18 | + Vector B[] = { Vector( b.get_draw_x(), b.get_draw_y() + b.get_height() ), |
| 19 | + Vector( b.get_draw_x() + b.get_width(), b.get_draw_y() + b.get_height() ), |
| 20 | + Vector( b.get_draw_x() + b.get_width(), b.get_draw_y() ), |
| 21 | + Vector( b.get_draw_x(), b.get_draw_y() ) |
| 22 | + }; |
| 23 | + |
| 24 | + for (auto& v : A) { |
| 25 | + v = rotate(v - a.get_center(), angleOfA) + a.get_center(); |
| 26 | + } |
| 27 | + |
| 28 | + for (auto& v : B) { |
| 29 | + v = rotate(v - b.get_center(), angleOfB) + b.get_center(); |
| 30 | + } |
| 31 | + |
| 32 | + Vector axes[] = { norm(A[0] - A[1]), norm(A[1] - A[2]), norm(B[0] - B[1]), norm(B[1] - B[2]) }; |
| 33 | + |
| 34 | + for (auto& axis : axes) { |
| 35 | + float P[4]; |
| 36 | + |
| 37 | + for (int i = 0; i < 4; ++i) P[i] = dot(A[i], axis); |
| 38 | + |
| 39 | + float minA = *std::min_element(P, P + 4); |
| 40 | + float maxA = *std::max_element(P, P + 4); |
| 41 | + |
| 42 | + for (int i = 0; i < 4; ++i) P[i] = dot(B[i], axis); |
| 43 | + |
| 44 | + float minB = *std::min_element(P, P + 4); |
| 45 | + float maxB = *std::max_element(P, P + 4); |
| 46 | + |
| 47 | + if (maxA < minB || minA > maxB) |
| 48 | + return false; |
| 49 | + } |
| 50 | + |
| 51 | + return true; |
| 52 | + } |
| 53 | + |
| 54 | +private: |
| 55 | + static inline float mag(const Vector& p){ |
| 56 | + return std::sqrt(p.x * p.x + p.y * p.y); |
| 57 | + } |
| 58 | + static inline Vector norm(const Vector& p){ |
| 59 | + return p * (1.f / mag(p)); |
| 60 | + } |
| 61 | + static inline float dot(const Vector& a, const Vector& b){ |
| 62 | + return a.x * b.x + a.y * b.y; |
| 63 | + } |
| 64 | + static inline Vector rotate(const Vector& p, float angle){ |
| 65 | + float cs = std::cos(angle), sn = std::sin(angle); |
| 66 | + return Vector ( p.x * cs - p.y * sn, p.x * sn + p.y * cs ); |
| 67 | + } |
| 68 | +}; |
| 69 | + |
| 70 | +#endif |
0 commit comments