Top down car physics

It's arcadey, not realistic!

by Ben Gillbanks

HTML

<canvas id="gameCanvas"></canvas>

CSS

body {
    background: #eee;
}
canvas {
    background: white;
}

JavaScript

// Get the canvas and context
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 400;

// Add rotation and velocity properties to the player
const player = {
  x: canvas.width / 2,
  y: canvas.height / 2,
  friction: 0.95,
  width: 10,
  height: 16,
  speed: 0,
  rotation: 0,
  rotationSpeed: 0.05,
  turnAngle: 0, // this will determine the desired turning direction
  turnSpeed: 0.05, // this will determine how quickly the vehicle turns
  turnFriction: 0.95, // friction will slow down the turning
  velocity: { x: 0, y: 0 },
  maxSpeed: 3,
    driftFactor: 0.9, // we apply this when turning while moving fast
  turnSpeedWhileMoving: 0.02, // slow down the turn rate when moving
};

// Update function
function update() {
  
  doControls();

// Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  

  // Update velocity based on rotation
  player.velocity.x = Math.sin(player.rotation) * player.speed;
  player.velocity.y = -Math.cos(player.rotation) * player.speed;

  // Update player position
  player.x += player.velocity.x;
  player.y += player.velocity.y;
  
  drawCar();

  // Call update again
  requestAnimationFrame(update);
  
}

function doControls() {
  let drift = Math.abs(player.speed) > player.maxSpeed / 2;
  
  // Accelerate forward and backward based on up and down keys
  if (keyState['ArrowUp']) {
    player.speed += 0.1;
  }
  if (keyState['ArrowDown'] && player.speed > -player.maxSpeed) {
    player.speed -= 0.1;
  }

// Adjust player's turnAngle based on left and right keys
  if ( Math.abs( player.speed ) > 0.1 ) {
      if (keyState['ArrowLeft']) {
        player.turnAngle -= player.rotationSpeed;
      }
      if (keyState['ArrowRight']) {
        player.turnAngle += player.rotationSpeed;
      }  
  }

  // Drifting behavior
  if (drift) {
    // Turn the vehicle into the drift direction
    if ( Math.abs(player.turnAngle) >0.1) {
	    player.speed *=...