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
|
#include <iomanip>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <array>
struct Point {
int x,
y;
Point() : x {0}, y {0} {}
Point(int x_arg, int y_arg) : x { x_arg }, y { y_arg } {}
};
class Rect {
public:
// 0) top left; 1) top right; 2) bottom left 3) bottom right
std::array<Point, 4> corners;
int height,
width;
bool initialized;
Rect() : height {0}, width {0}, initialized {false} {}
Rect(Point topleft, Point bottomright)
{
corners.at(0) = topleft;
corners.at(3) = bottomright;
calcHeight();
calcWidth();
corners.at(1).x = bottomright.x;
corners.at(1).y = topleft.y;
corners.at(2).x = topleft.x;
corners.at(2).y = bottomright.y;
initialized = true;
}
// Warning! detectCollide() may throw std::invalid_argument
bool detectCollide(const Rect* rhs) {
if(!initialized || !rhs->initialized) {
throw std::invalid_argument("Rectangle not initialized.");
}
if(!height) { calcHeight(); }
if(!width) { calcWidth(); }
int x = corners.at(0).x;
int rx = rhs->corners.at(0).x;
bool xOverlap = valueInRange(x, rx, rx + rhs->width)
|| valueInRange(rx, x, x + width);
int y = corners.at(0).y;
int ry = rhs->corners.at(0).y;
bool yOverlap = valueInRange(y, ry, ry + rhs->height)
|| valueInRange(ry, y, y + height);
return xOverlap && yOverlap;
}
private:
void calcHeight() { height = corners.at(3).y - corners.at(0).y; }
void calcWidth() { width = corners.at(3).x - corners.at(0).x; }
bool valueInRange (int value, int min, int max)
{ return (value >= min) && (value <= max); }
};
class Player : public Rect {
public:
Player(Point topleft, Point bottomright) : Rect(topleft, bottomright) {}
};
class Object : public Rect {
public:
Object(Point topleft, Point bottomright) : Rect(topleft, bottomright) {}
};
void waitForEnter();
int main()
{
Player p1 { {1, 1}, {5, 3} };
Object o1 { {4, 3}, {8, 6} };
std::cout << "Object collision: " << std::boolalpha
<< p1.detectCollide(&o1) << '\n';
Player p2 { {1, 1}, {5, 3} };
Object o2 { {6, 3}, {8, 6} };
std::cout << "Object collision: " << std::boolalpha
<< p2.detectCollide(&o2) << '\n';
waitForEnter();
return 0;
}
void waitForEnter()
{
std::cout << "\nPress ENTER to continue...\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
| |