Skip to content

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:

  1. Front Left โ†–๏ธ
  2. Front Right โ†—๏ธ
  3. Rear Left โ†™๏ธ
  4. 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
);