 # Intersection tests (AABB and SAT)

Sep 23rd, 2016
174
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. #include <cmath>
2.
3. //AABB intersection test
4. bool isColliding(const Entity& lhs, const Entity& rhs) {
5.     SDL_assert(&lhs != &rhs);
6.     return !(lhs._x + lhs._width < rhs._x ||
7.         rhs._x + rhs._width < lhs._x ||
8.         lhs._y + lhs._height < rhs._y ||
9.         rhs._y + rhs._height < lhs._y);
10. }
11.
12. //SAT intersection test. http://www.metanetsoftware.com/technique/tutorialA.html
13. //Many thanks to Jerry Jonsson and Tommi Lipponen at Uppsala University, GAME,
14. //for the original implementation of this function: http://pastebin.com/cbJWTfb9
15. bool getOverlap(const Entity& lhs, const Entity& rhs, int& overlapX, int& overlapY) {
16.     SDL_assert(&lhs != &rhs);
17.     overlapX = 0;
18.     overlapY = 0;
19.     int centerDeltaX = static_cast<int>(lhs.centerX() - rhs.centerX());
20.     int halfWidths = (lhs._width + rhs._width) / 2;
21.
22.     if (std::abs(centerDeltaX) > halfWidths) return false; //no overlap on x == no collision
23.
24.     int centerDeltaY = static_cast<int>(lhs.centerY() - rhs.centerY());
25.     int halfHeights = (lhs._height + rhs._height) / 2;
26.
27.     if (std::abs(centerDeltaY) > halfHeights) return false; //no overlap on y == no collision
28.
29.     int dx = halfWidths - std::abs(centerDeltaX); //overlap on x
30.     int dy = halfHeights - std::abs(centerDeltaY); //overlap on y
31.     if (dy < dx) {
32.         overlapY = (centerDeltaY < 0) ? -dy : dy;
33.     } else if (dy > dx) {
34.         overlapX = (centerDeltaX < 0) ? -dx : dx;
35.     } else {
36.         overlapX = (centerDeltaX < 0) ? -dx : dx;
37.         overlapY = (centerDeltaY < 0) ? -dy : dy;
38.     }
39.     return true;
40. }
RAW Paste Data