TrackPath
Responsible for:
- Converting SVG paths to usable track data
- Generating evenly spaced checkpoints
- Centering and scaling track layouts
- Supporting path manipulations (reversing, reducing points)
- Calculating positional relationships
ποΈ Constructor
constructor(path: string, numPoints: number)| Parameter | Type | Description |
|---|---|---|
path | string | SVG path data (e.g., βM0,0 L100,100β) |
numPoints | number | Checkpoints to generate along path |
π The constructor immediately processes the path into sampled checkpoints
π Properties
| Property | Type | Description |
|---|---|---|
path | string | Original SVG path data |
sampledPoints | CheckPoint[] | Processed checkpoints array |
π οΈ Methods
Path Processing
_processCheckpoints(numPoints: number)
graph TD A[Parse SVG] --> B[Extract Points] B --> C[Calculate Total Length] C --> D[Sample Evenly] D --> E[Store as CheckPoints]_getWidthAndHeight()
Calculates track boundaries:
{ width: maxX - minX, height: maxY - minY}Spatial Transformations
centerTrackPath(canvasW, canvasH, offset)
Centering algorithm:
- Calculate track dimensions
- Determine center offset
- Apply positional adjustment
- Incorporate manual offset
reduce(numPoints)
Optimization flow:
- Keeps every Nth point
- Maintains path shape
- Reduces computational load
reverse()
Reverses checkpoint order:
this.sampledPoints.reverse();Measurement
getDistanceToPoint(pos, pointId)
Calculates:
- Segment between pointId-1 and pointId+1
- Projects position to segment
- Returns perpendicular distance
ποΈ Factory Method
createFromPath(...)
Complete track initialization pipeline:
static createFromPath( path: string, numPoints: number, displayDriver: DisplayDriver, pathOffset: Vec2D, scale: number, pointOffset = 20): TrackPathProcess Flow:
- Create raw TrackPath
- Center in canvas
- Apply scaling
- Shift start position
- Return processed path
π Data Structures
CheckPoint
interface CheckPoint { x: number; y: number; width?: number; // Optional road width angle?: number; // Optional segment angle}Vec2D
type Vec2D = { x: number; y: number;}π¦ Usage Example
Basic Initialization
const ovalTrack = new TrackPath( "M0,0 Q50,100 100,0 Q150,100 200,0", 100);Full Production Setup
const racePath = TrackPath.createFromPath( svgData, 200, renderer, {x: 50, y: 50}, 1.5, 30);
// Get distance to checkpoint #42const dist = racePath.getDistanceToPoint( {x: playerX, y: playerY}, 42);π‘ Pro Tip: Use
reduce()for performance-critical scenarios where precise checkpoint spacing isnβt crucial.
π¨ Design Note: Maintain SVG paths in vector editors for easy track design iteration.