Skip to content

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)
ParameterTypeDescription
pathstringSVG path data (e.g., β€œM0,0 L100,100”)
numPointsnumberCheckpoints to generate along path

πŸ“Œ The constructor immediately processes the path into sampled checkpoints


πŸ“Š Properties

PropertyTypeDescription
pathstringOriginal SVG path data
sampledPointsCheckPoint[]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:

  1. Calculate track dimensions
  2. Determine center offset
  3. Apply positional adjustment
  4. 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:

  1. Segment between pointId-1 and pointId+1
  2. Projects position to segment
  3. Returns perpendicular distance

🏎️ Factory Method

createFromPath(...)

Complete track initialization pipeline:

static createFromPath(
path: string,
numPoints: number,
displayDriver: DisplayDriver,
pathOffset: Vec2D,
scale: number,
pointOffset = 20
): TrackPath

Process Flow:

  1. Create raw TrackPath
  2. Center in canvas
  3. Apply scaling
  4. Shift start position
  5. 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 #42
const 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.