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 *=...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.