ProjectsGame-DevJavaScriptCanvas
Build a 2D Platformer in the Browser (HTML5 Canvas)
3.94 min read
Md Nasim Sheikh
Modern engines hide the logic from you. To truly understand how Mario jumps, you need to write the physics yourself.
Advertisement
The HTML Setup
All you need is a <canvas>.
<canvas id="game" width="800" height="600"></canvas>
<script src="game.js"></script>
The Game Loop
Games are just infinite loops running 60 times per second.
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
function update() {
// 1. Update Physics
player.y += player.velocity_y;
player.velocity_y += GRAVITY; // 0.5
// 2. Clear Screen
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 3. Draw Player
ctx.fillStyle = 'red';
ctx.fillRect(player.x, player.y, player.width, player.height);
requestAnimationFrame(update);
}
const player = { x: 100, y: 100, velocity_y: 0, width: 30, height: 30 };
const GRAVITY = 0.5;
requestAnimationFrame(update);
Collision Detection (AABB)
Axis-Aligned Bounding Box. It checks if two rectangles overlap.
function checkCollision(rect1, rect2) {
if (rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y) {
return true; // Collision!
}
return false;
}
If a collision is detected with the "ground", you set velocity_y = 0 and snap the player on top of the block.
Advertisement
Quiz
Quick Quiz
Why do we use 'requestAnimationFrame' instead of 'setInterval' for the game loop?
Conclusion
Writing a physics engine from scratch is humbling. You will appreciate Unity's "Add Component: Rigidbody" button much more after debugging why your character falls through the floor.
Written by
Md Nasim Sheikh
Software Developer at softexForge
Verified Author150+ Projects
Published: