Collision Code
From WorkCDN
This is a set of basic collision routines I have written. It's geometry based, not physics. It's currently coded in C++ with fast integer operations. I will at some point in the future try to expand this with some documentation. These collision routines in the public domain. Feel free to use and abuse at will.
#ifndef COLLISION_H_ #define COLLISION_H_ namespace collision { inline bool point_point(const int x1, const int y1, const int x2, const int y2) { return x1 == x2 && y1 == y2; } inline bool point_hline(const int x1, const int y1, const int y2) { return y1 == y2; } inline bool point_vline(const int x1, const int y1, const int x2) { return x1 == x2; } inline bool point_aabox(const int x, const int y, const int l, const int t, const int r, const int b) { return x >= l && x <= r && y >= t && y <= b; } inline bool point_circle(const int x, const int y, const int cx, const int cy, const int r) { return ((cx-x)*(cx-x) + (cy-y)*(cy-y)) <= (r*r); } inline bool hline_hline(const int y1, const int y2) { return y1 == y2; } inline bool hline_aabox(const int y, const int l, const int t, const int r, const int b) { return y >= t && y <= b; } inline bool hline_circle(const int y, const int cx, const int cy, const int r) { return ((cy>y) ? (cy-y) : (y-cy)) <= r; } inline bool vline_vline(const int x1, const int x2) { return x1 == x2; } inline bool vline_aabox(const int x, const int l, const int t, const int r, const int b) { return x >= l && x <= r; } inline bool vline_circle(const int x, const int cx, const int cy, const int r) { return ((cx>x) ? (cx-x) : (x-cx)) <= r; } inline bool aabox_aabox(const int l1, const int t1, const int r1, const int b1, const int l2, const int t2, const int r2, const int b2) { return (l1 <= r2) && (r1 >= l2) && (t1 <= b2) && (b1 >= t2); } inline bool aabox_circle(const int l, const int t, const int r, const int b, const int cx, const int cy, const int cr) { if (point_aabox(cx, cy, l, t, r, b)) return true; // if the center point is in the box we definitely collided if (cy <= t) { if (cx <= l) { // check distance to top left point return point_circle(l, t, cx, cy, cr); } if (cx >= r) { return point_circle(r, t, cx, cy, cr); } else { // its above the top segment return (t - cy) <= cr; } } if (cy >= b) { if (cx >= r) { // check distance to bottom right point return point_circle(r, b, cx, cy, cr); } if (cx <= l) { // bottom left return point_circle(l, b, cx, cy, cr); } else { // its below the bottom segment return (cy - b) <= cr; } } else { // Center is between the top and bottom segments // Check the side segments with VLine code if (cx <= l) { // its to the left return (l - cx) <= cr; } else { // must be to the right return (cx - r) <= cr; } } } inline bool circle_circle(const int cx1, const int cy1, const int r1, const int cx2, const int cy2, const int r2) { return ((cx1-cx2)*(cx1-cx2) + (cy1-cy2)*(cy1-cy2)) <= ((r1 + r2) * (r1 + r2)); } } #endif /*COLLISION_H_*/
