Drawing a whole level with spr() one tile at a time would be painful. Instead you paint the level once in the Map tab, and draw the entire thing with a single call: map().
1. Paint a level
First make a couple of tiles in the Sprites tab — say a grass tile in slot 1 and a wall in slot 2. Then open the Map tab: pick a sprite from the sheet and paint it onto the grid. The map is 32 × 32 tiles, and each tile is 8 pixels, so the full map is 256 × 256 pixels — bigger than the 128 × 128 screen.
2. Draw the map
map() stamps every non-empty cell of the map onto the screen. With no arguments it draws from the top-left corner:
function draw() {
cls(0);
map(); // draw the whole tile map at (0, 0)
}You will see the top-left 128 × 128 chunk of your level — that is as much as fits on screen at once. To see the rest, we scroll.
3. Scroll the level
map(x, y) shifts the whole map by an offset. Passing negative values slides the map left/up, which reveals what is further right/down — exactly like a camera panning across the world. Move the offset with the arrow keys:
let camX = 0;
let camY = 0;
function update() {
if (key('ArrowRight')) {
camX += 2;
}
if (key('ArrowLeft')) {
camX -= 2;
}
if (key('ArrowDown')) {
camY += 2;
}
if (key('ArrowUp')) {
camY -= 2;
}
camX = mid(0, camX, 256 - 128); // do not scroll past the edges
camY = mid(0, camY, 256 - 128);
}
function draw() {
cls(0);
map(-camX, -camY); // negative offset = camera moves right/down
spr(0, 60, 60); // the player stays centered on screen
}Why negative? To make the camera move right, everything else has to slide left. So a camera position of camX draws the map at -camX. The clamp stops you scrolling past the 256-pixel map into empty space.
What you learned
- Tiles are sprites painted onto the grid in the Map tab.
- The map is 32 × 32 tiles (256 × 256 pixels), larger than the screen.
map()draws the whole map;map(x, y)shifts it by an offset.- Scroll with a negative offset (
map(-camX, -camY)) to pan a camera across the level.