Collision Management
This module provides essential geometric calculations for collision detection in 2D space, particularly useful for game physics and object interaction systems. ๐ฎ
๐ข Core Functions
getCarCorners(position: Vec2D, width: number, height: number, angle: number): Vec2D[] ๐
Calculates the four corner points of a rotated rectangular car shape. ๐
Parameters:
position: Center position of the car ๐ฏwidth: Width of the carโs collision box โ๏ธheight: Height of the carโs collision box โ๏ธangle: Rotation angle in degrees ๐
Returns: Array of 4 corner points in order:
- Front Left โ๏ธ
- Front Right โ๏ธ
- Rear Left โ๏ธ
- Rear Right โ๏ธ
Note: โ ๏ธ The function includes a fixed offset (+30, +15) to align the collision box with the visual representation. This should be investigated and potentially made configurable. ๐
rayCast(from: Vec2D, to: Vec2D, corners: Vec2D[]): Vec2D | null ๐ฆ
Performs ray casting against a polygon defined by corners. ๐ฅ
Parameters:
from: Starting point of the ray ๐to: Ending point of the ray ๐corners: Array of points defining the polygon ๐ฆ
Returns:
Intersection point closest to from, or null if no intersection โ
Performance Note: โฑ๏ธ This operation can be computationally expensive - use sparingly. ๐ป
lineToRectDistance(from: Vec2D, to: Vec2D, rect: Vec2D[]): number ๐
Calculates the minimum distance between a line segment and a rectangle. ๐
Parameters:
from: Start point of line segment ๐ ฐ๏ธto: End point of line segment ๐ ฑ๏ธrect: Array of 4 points defining rectangle corners ๐ง
Returns: Minimum distance between the line segment and rectangle edges ๐ข
๐ง Supporting Functions
getIntersection(from, to, p1, p2): Vec2D | null โ๏ธ
Finds intersection point between two line segments using linear algebra. โ
onSegment(p, q, r): boolean ๐
Determines if point q lies on segment pr. โ๏ธ
distance(a, b): number ๐
Standard Euclidean distance between two points. ๐งฎ
distanceToSegment(p, v, w): number ๐
Calculates distance from point p to line segment vw. ๐
๐ Usage Examples
// Calculate car collision corners ๐const corners = getCarCorners( {x: 100, y: 100}, 50, // width โ๏ธ 100, // height โ๏ธ 45 // angle in degrees ๐);
// Check ray intersection ๐ฆconst hitPoint = rayCast( {x: 0, y: 0}, {x: 200, y: 200}, obstacleCorners);
// Get minimum distance to rectangle ๐const dist = lineToRectDistance( {x: 50, y: 50}, {x: 150, y: 150}, rectCorners);