Untitled
unknown
plain_text
2 years ago
1.5 kB
2
Indexable
class Car { constructor(x, y, color) { this.x = x; this.y = y; this.color = color; this.speed = 0; this.maxSpeed = 10; this.friction = 0.99; this.acceleration = 1; this.turningSpeed = 0.05; } move(steering, dt) { // calculate speed change due to acceleration let accelerationSpeedChange = this.acceleration * steering * dt; // apply speed change, clamping at max speed this.speed = Math.min(this.speed + accelerationSpeedChange, this.maxSpeed); // calculate distance traveled let distance = this.speed * dt; // calculate speed reduction due to friction this.speed *= this.friction; // return the distance traveled return distance; } draw(ctx) { ctx.save(); ctx.translate(this.x, this.y); ctx.rotate(this.speed / this.maxSpeed * this.turningSpeed); ctx.fillStyle = this.color; ctx.fillRect(-50, -10, 100, 20); ctx.restore(); } } class Game { constructor(canvas) { this.canvas = canvas; this.ctx = canvas.getContext('2d'); this.cars = []; this.car = new Car(canvas.width / 2, canvas.height / 2, 'red'); this.cars.push(this.car); this.time = 0; } step(dt) { this.time += dt; this.car.move(Math.sin(this.time), dt); this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); for (let car of this.cars) { car.draw(this.ctx); } requestAnimationFrame(this.step.bind(this)); } } let canvas = document.getElementById('canvas'); let game = new Game(canvas); game.step(16);
Editor is loading...
Leave a Comment