š§® Game Physics
Master velocity, acceleration, gravity, and realistic physics simulation for engaging gameplay!
Your Progress
0 / 9 completedš Sections
Introduction to Game Physics
Section 1 of 9
Game physics simulates real-world physics in your games, making movement feel natural and realistic. Understanding position, velocity, and acceleration is fundamental. **Core Physics Concepts:** **Position (x, y):** Where an object is located in 2D space. Measured in pixels from origin (usually top-left corner). **Velocity (vx, vy):** How fast an object moves. Measured in pixels per second. ⢠Positive velocity ā Moving right/down ⢠Negative velocity ā Moving left/up ⢠Zero velocity ā Stationary **Acceleration (ax, ay):** How fast velocity changes. Measured in pixels per second squared. ⢠Gravity is constant downward acceleration ⢠Engines provide acceleration ⢠Friction causes deceleration **The Physics Chain:** Acceleration ā Changes Velocity ā Changes Position **Real-World Example:** ⢠Car accelerates (increasing velocity) ⢠Reaches max speed (velocity constant) ⢠Brakes (negative acceleration, decreasing velocity) ⢠Stops (velocity = 0) **Why Physics Matters:** ⢠Realistic jumping and falling ⢠Natural movement and momentum ⢠Projectile trajectories ⢠Vehicle handling ⢠Character weight and inertia
Code Example:
// 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);š” Tip: Try this code in your browser console (F12 ā Console).