1 module prova.collision.intersects; 2 3 import prova.collision, 4 prova.math, 5 std.math; 6 7 bool pointIntersectsPoint(PointCollider pointA, PointCollider pointB) 8 { 9 return pointA.getPosition() == pointB.getPosition(); 10 } 11 12 bool pointIntersectsCircle(PointCollider point, CircleCollider circle) 13 { 14 const float distance = point.getPosition().distanceTo(circle.getPosition()); 15 16 return distance <= circle.radius; 17 } 18 19 bool pointIntersectsRect(PointCollider point, RectCollider rect) 20 { 21 Vector2 position = point.getPosition(); 22 Rect bounds = rect.getBounds(); 23 24 return position.x > bounds.left && position.x < bounds.left + bounds.width && 25 position.y < bounds.top && position.y > bounds.top - bounds.height; 26 } 27 28 bool circleIntersectsCircle(CircleCollider circleA, CircleCollider circleB) 29 { 30 const float distance = circleA.getPosition().distanceTo(circleB.getPosition()); 31 32 return distance < circleA.radius + circleB.radius; 33 } 34 35 bool circleIntersectsRect(CircleCollider circle, RectCollider rect) 36 { 37 // Following answer provided by e.James https://stackoverflow.com/users/33686/e-james 38 // https://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection 39 40 const Vector2 circlePosition = circle.getPosition(); 41 const Vector2 rectPosition = rect.getPosition(); 42 43 const Vector2 distance = Vector2( 44 abs(circlePosition.x - rectPosition.x), 45 abs(circlePosition.y - rectPosition.y) 46 ); 47 48 if(distance.x >= rect.width / 2 + circle.radius) 49 return false; 50 if(distance.y >= rect.height / 2 + circle.radius) 51 return false; 52 53 if(distance.x < rect.width / 2) 54 return true; 55 if(distance.y < rect.height / 2) 56 return true; 57 58 const float cornerDistSquared = (distance.x - rect.width / 2) ^^ 2 + 59 (distance.y - rect.height / 2) ^^ 2; 60 61 return cornerDistSquared < circle.radius ^^ 2; 62 } 63 64 bool rectIntersectsRect(RectCollider rectA, RectCollider rectB) 65 { 66 Rect boundsA = rectA.getBounds(); 67 Rect boundsB = rectB.getBounds(); 68 69 return boundsA.left < boundsB.right && 70 boundsA.right > boundsB.left && 71 boundsA.top > boundsB.bottom && 72 boundsA.bottom < boundsB.top; 73 }