Gravity in a platformer is one line: every physics step, add a little to the vertical speed. Collisions are the interesting part, and the method that keeps them simple is to move one axis at a time: move horizontally and fix any overlap with the tiles, then move vertically and fix any overlap again. In part 2 of our JavaScript platformer tutorial, Cubi gets both: he walks off ledges, lands on platforms, and turns around when he hits a wall.
We continue from the code of part 1, the canvas and the game loop. Only the parts that change are shown here; the demo at the end has the complete file.
Step 1: gravity is an acceleration
A common first attempt is to move the character down a fixed number of pixels per second. It looks wrong: real things fall slowly at first and faster every moment. That is because gravity is not a speed, it is an acceleration: it adds speed. Cubi gets a vertical speed, vy, and gravity adds 1500 pixels per second to it, every second.
const TILE = 32;
const COLS = 16;
const ROWS = 9;
const VIEW_W = COLS * TILE; // 512
const VIEW_H = ROWS * TILE; // 288
const STEP = 1 / 60;
// Gravity is an acceleration: it adds speed every second.
const GRAVITY = 1500; // px/s²
const MAX_FALL = 600; // px/s: 10 px per step, less than a tileThe second number, MAX_FALL, is a speed limit for falling. Games use it so a long fall stays readable instead of turning into a blur, and we use it for one more reason we will see in a moment.
Step 2: the level as a grid
In part 1 the blocks were only drawn. Now the physics needs to ask the level a question: is there something solid at this spot? The easiest way to answer is a grid with the same shape as the world, 16 columns by 9 rows, where each cell holds 1 for a brick and 0 for air.
const GROUND_ROW = 7;
const BLOCKS = [
[1, 3], [2, 3], [3, 3], // where Cubi starts
[5, 5], [6, 5], [7, 5], // a lower platform
[11, 3], [12, 3],
[1, 6], // a step
[14, 5], [14, 6], // a wall
];
// level[row][col]: 1 is a brick, 0 is air.
const level = [];
for (let row = 0; row < ROWS; row++) {
level.push(new Array(COLS).fill(row >= GROUND_ROW ? 1 : 0));
}
for (const [col, row] of BLOCKS) level[row][col] = 1;
function isSolid(col, row) {
// The sides of the screen behave as walls.
if (col < 0 || col >= COLS) return true;
if (row < 0) return false;
if (row >= ROWS) return true;
return level[row][col] === 1;
}isSolid(col, row) is the only question the physics will ever ask the level. Outside the screen on the left and right it answers "solid", so the sides behave as walls and Cubi cannot run off the screen. Above the top it answers "air", so nothing gets stuck on the ceiling of the screen.
In part 4 this grid will be built from a map written as text, which is much nicer to design with. The physics will not notice: it will keep calling isSolid().
Step 3: Cubi's new state
Two new fields: vy, the vertical speed, positive going down (the canvas counts y from the top), and onGround, which tells whether he is standing on something. Nobody reads onGround yet, but jumping will need it: you can only jump from the ground.
const START = { x: 1 * TILE, y: 2 * TILE };
const player = {
x: START.x,
y: START.y,
w: TILE,
h: TILE,
speed: 120,
dir: 1,
vy: 0, // vertical speed, px/s, positive is down
onGround: false,
sprite: null,
};Cubi now starts on the high platform on the left, so the first thing he does is walk off it.
Step 4: collisions, one axis at a time
Cubi and every tile are boxes aligned with the axes, the simplest case of collision detection (often called AABB). The plan is always the same: move, see which tiles the box overlaps, and if any of them is solid, push the box back out.
The question is out in which direction. If Cubi moves right and down in the same step and ends up overlapping the corner of a block, there is no way to know whether he hit a wall or landed on a floor. Moving one axis at a time removes the doubt: after moving only horizontally, any overlap must be a wall; after moving only vertically, it must be a floor or a ceiling.
There is a second advantage: we only check the tiles under the box. A 32 by 32 box covers at most two columns and two rows, so each move asks isSolid() two or three times, never for the whole level.
// The box ends AT x + w: EDGE keeps that end out of the next tile.
const EDGE = 0.001;
function moveX(dt) {
player.x += player.speed * player.dir * dt;
const top = Math.floor(player.y / TILE);
const bottom = Math.floor((player.y + player.h - EDGE) / TILE);
const col = player.dir > 0
? Math.floor((player.x + player.w - EDGE) / TILE) // right side
: Math.floor(player.x / TILE); // left side
for (let row = top; row <= bottom; row++) {
if (isSolid(col, row)) {
// Right against the wall, and turn around.
player.x = player.dir > 0 ? col * TILE - player.w : (col + 1) * TILE;
player.dir = -player.dir;
return;
}
}
}To convert a position to a tile we divide by the tile size and round down: Math.floor(x / TILE). The edge needs one detail. A box at x = 0 with a width of 32 covers from 0 up to 32, without including 32, which is where the next tile begins. Without EDGE, Cubi standing perfectly still next to a wall would count as being inside it.
When he hits a wall we place him right against it and flip his direction. In part 3 a swipe will also flip it; for now the walls do it.
The vertical move follows the same pattern, with gravity added first:
function moveY(dt) {
player.vy = Math.min(player.vy + GRAVITY * dt, MAX_FALL);
player.y += player.vy * dt;
player.onGround = false;
const left = Math.floor(player.x / TILE);
const right = Math.floor((player.x + player.w - EDGE) / TILE);
const falling = player.vy > 0;
const row = falling
? Math.floor((player.y + player.h - EDGE) / TILE) // feet
: Math.floor(player.y / TILE); // head
for (let col = left; col <= right; col++) {
if (isSolid(col, row)) {
if (falling) {
// Land: exactly on top of the tile.
player.y = row * TILE - player.h;
player.onGround = true;
} else {
// Bump the head (it will matter once Cubi can jump).
player.y = (row + 1) * TILE;
}
player.vy = 0;
return;
}
}
}Landing is where that pattern pays off. We know he was falling, so the solid tile is under his feet, and we can put him exactly on top of it: row * TILE - player.h, a whole number, with no pixel of overlap. Bumping into a ceiling cannot happen yet, but it will as soon as he can jump, and it is the same code reversed.
Step 5: update, and the ledges for free
The order inside update() is horizontal first, then vertical. Drawing now walks over the same grid the physics uses, so what you see is exactly what collides.
function update(dt) {
moveX(dt);
moveY(dt);
}
function draw() {
ctx.fillStyle = SKY;
ctx.fillRect(0, 0, VIEW_W, VIEW_H);
// The same grid the physics uses: what you see is what collides.
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
if (level[row][col] === 1) drawBrick(col, row);
}
}
drawPlayer();
}Notice what is missing: there is no code for ledges. Gravity pulls on every step, even while Cubi is standing, and the floor pushes him back up in the same step. The moment he walks past the end of a platform there is no floor to push back, so he starts to fall. Standing and falling are the same code.
Why Cubi never goes through the floor
Collisions like these check where the box ends up, not the path it took. If something moved 40 pixels in one step it could jump right over a 32-pixel tile without ever overlapping it, the bug known as tunneling. Two decisions keep it away here: the fixed step from part 1, which keeps every step at exactly 1/60 of a second even on a slow phone, and MAX_FALL, which caps a fall at 600 pixels per second. 600 divided by 60 is 10 pixels per step, always less than a tile.
The box is not always the drawing
Everything here works on Cubi's box, not on his drawing. For Cubi they are the same square, but most characters are not square: a round enemy, or one with spikes, needs a box that does not match its picture, and the game feels unfair when the two are far apart. We will look at that properly when the enemies arrive. In the demo, the ▢ button draws Cubi's box and the tiles it is touching, so you can see what the physics sees.
Try it
Cubi walks off the high platform, lands on the one below, drops to the ground, and goes back and forth between the wall and the step. ↺ drops him from the start again (or press R), and ▢ shows the collision boxes (or press B).
The file is the complete game up to this point, with its comments in English, Spanish and Portuguese. Try changing GRAVITY: at 500 Cubi floats like he is on the Moon, at 3000 he drops like a stone. Or move the blocks around and watch him find his way.
Next Monday: controls
In part 3 Cubi stops being a spectator: a button to jump, a swipe to turn around, and the keyboard on a computer. That is where onGround and the ceiling collision start to matter. Meanwhile, you can play the games we make at Raptware on our games page.
Did Cubi get stuck in a brick? Leave your question in the comments and we will look at it together.
Comments
Sign in with your Raptware account to leave a comment.
Personal details
Sorry, this site is made for kids and adults alike, so we can't allow sharing personal details. Thank you for understanding, and for your comments!