• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# Intersection tests (AABB, SAT, lineCircle, distance) ulfben   Nov 22nd, 2016 (edited) 154 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /*Math from "Making Thing Move!" by Keith Peters*/
2. public static function lineCircleIntersection(lineStart:Point, lineEnd:Point, entity:Entity):Boolean {
3.     var angle:Number = Math.atan2((lineEnd.y-lineStart.y), (lineEnd.x-lineStart.x));
4.     var dx:Number = entity.centerX-((lineStart.x+lineEnd.x) * 0.5);
5.     var dy:Number = entity.centerY-((lineStart.y+lineEnd.y) * 0.5);
6.     return (Math.abs(Math.cos(angle)*dy - Math.sin(angle)*dx) < entity.radius);
7. }
8.
9. public static function distanceSq(lhs:Entity, rhs:Entity):Number{
10.     var dx:Number = lhs.centerX - rhs.centerX;
11.     var dy:Number = lhs.centerY - rhs.centerY;
12.     return (dx * dx + dy * dy);
13. }
14.
15. public static function distance(lhs:Entity, rhs:Entity):Number{
16.     var dx:Number = lhs.centerX - rhs.centerX;
17.     var dy:Number = lhs.centerY - rhs.centerY;
18.     return Math.sqrt(dx * dx + dy * dy);
19. }
20.
21. public static function intersectsAABB(lhs:core.Entity, rhs:core.Entity):Boolean {
22.     return !(lhs.right < rhs.left
23.             || rhs.right < lhs.left
24.             || lhs.bottom < rhs.top
25.             || rhs.bottom < lhs.top);
26. }
27.
28. //SAT intersection test. http://www.metanetsoftware.com/technique/tutorialA.html
29. //returns true on intersection, and sets the least intersecting axis in overlap
30. public static function getOverlap(lhs:Entity, rhs:Entity, overlap:Point):Boolean {
31.     overlap.setTo(0, 0);
32.     var centerDeltaX:Number = lhs.centerX - rhs.centerX;
33.     var halfWidths:Number = (lhs.width + rhs.width) * 0.5;
34.
35.     if (Math.abs(centerDeltaX) > halfWidths) return false; //no overlap on x == no collision
36.
37.     var centerDeltaY:Number = lhs.centerY - rhs.centerY;
38.     var halfHeights:Number = (lhs.height + rhs.height) * 0.5;
39.
40.     if (Math.abs(centerDeltaY) > halfHeights) return false; //no overlap on y == no collision
41.
42.     var dx:Number = halfWidths - Math.abs(centerDeltaX); //overlap on x
43.     var dy:Number = halfHeights - Math.abs(centerDeltaY); //overlap on y
44.     if (dy < dx) {
45.         overlap.y = (centerDeltaY < 0) ? -dy : dy;
46.     } else if (dy > dx) {
47.         overlap.x = (centerDeltaX < 0) ? -dx : dx;
48.     } else {
49.         overlap.x = (centerDeltaX < 0) ? -dx : dx;
50.         overlap.y = (centerDeltaY < 0) ? -dy : dy;
51.     }
52.     return true;
53. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.
Top