Master gravity, velocity, acceleration, and realistic movement for game objects
Section 1 of 9
// Basic physics object
class PhysicsObject {
constructor(x, y) {
// Position
this.x = x;
this.y = y;
// Velocity (pixels per second)
this.vx = 0;
this.vy = 0;
// Acceleration (pixels per second squared)
this.ax = 0;
this.ay = 0;
// Object properties
this.mass = 1;
this.width = 50;
this.height = 50;
}
// Update physics (called every frame)
update(deltaTime) {
// Convert delta time to seconds
const dt = deltaTime / 1000;
// Acceleration affects velocity
this.vx += this.ax * dt;
this.vy += this.ay * dt;
// Velocity affects position
this.x += this.vx * dt;
this.y += this.vy * dt;
}
// Apply a force (F = ma, so a = F/m)
applyForce(fx, fy) {
this.ax += fx / this.mass;
this.ay += fy / this.mass;
}
// Reset acceleration each frame
resetAcceleration() {
this.ax = 0;
this.ay = 0;
}
}
// Example: Create and update object
const ball = new PhysicsObject(100, 100);
// Game loop
let lastTime = 0;
function gameLoop(currentTime) {
const deltaTime = currentTime - lastTime;
lastTime = currentTime;
// Reset acceleration
ball.resetAcceleration();
// Apply forces (gravity)
const gravity = 980; // pixels/s² (Earth gravity ~9.8 m/s²)
ball.applyForce(0, ball.mass * gravity);
// Update physics
ball.update(deltaTime);
// Draw ball
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'blue';
ctx.fillRect(ball.x, ball.y, ball.width, ball.height);
requestAnimationFrame(gameLoop);
}
requestAnimationFrame(gameLoop);Build a physics-based game demonstrating realistic movement:
Create expansive game worlds with tile-based maps and level editors