1. Vector Math on the HTML5 Canvas Coordinate Space
In 2D game development, physical movement and direction are modeled using vectors. A 2D vector represents a direction and magnitude. In a coordinate system, the canvas space has its origin (0, 0) at the top-left corner, meaning the Y-axis increases downward—a critical difference from Cartesian physics coordinates.
To update a player's position, the game loop adds the velocity vector to the position coordinates on each frame step. Acceleration is modeled by adding the acceleration vector to the velocity vector first, integrating physical friction or gravity decay parameters over time.
2. Vector Collision Normal Reflections
When a projectile collides with a wall or bumper, its trajectory must bounce realistically. The mathematical formula to reflect a velocity vector (V) off a surface with normal vector (N) requires standard vector dot product calculations.
First, normalize the surface normal vector N. The reflected velocity vector R is solved as: R = V - 2 × (V · N) × N. By adjusting the output velocity with a coefficient of restitution, developers simulate physical elasticity, letting projectiles lose energy or speed up on impact.
// Vector reflection formula in TypeScript
interface Vector2D { x: number; y: number; }
function reflect(velocity: Vector2D, normal: Vector2D, elasticity = 1.0): Vector2D {
const dotProduct = (velocity.x * normal.x) + (velocity.y * normal.y);
return {
x: (velocity.x - 2 * dotProduct * normal.x) * elasticity,
y: (velocity.y - 2 * dotProduct * normal.y) * elasticity
};
}3. Recursive Raycasting and Path Predictions
To render path predictions (e.g. standard dashes showing a projectile's bounce path before firing), modern canvas games execute a fast, recursive simulation step known as raycasting.
The raycaster steps the projectile forward in imaginary time steps, checking for intersections with boundary segments or bumper circles. Once a collision coordinates is resolved, the reflection math is applied to solve the new vector, and the path continues. This prediction loop is capped at a fixed number of reflections to prevent performance degradation on slower mobile processors.