Worlds, AI and multiplayer · 6 MIN READ

A camera is a coordinate transform: follow the target, clamp to the map, draw only visible tiles

Convert between tile, world and screen coordinates, keep a following camera inside the map and compute the exact range of tiles to draw.

The previous unit gave every entity a world position and a fixed-timestep update. A tile map lays a grid over that world, and a camera decides which part of it reaches the screen. Both are small pieces of arithmetic, and most tile-map bugs are one of three mistakes in it: the wrong coordinate space, the wrong rounding or the wrong edge.

gamedev · A MAP OF THE IDEA

  1. Center on target
  2. Clamp to map bounds
  3. Floor to tile range
  4. Draw range, snap camera

Useful when

  • Draw cost depends on the view size, not the map size.
  • One transform pair keeps drawing and picking consistent.

Watch out

  • int() truncation misplaces negative coordinates by one tile.
  • Rounding the camera inside the simulation makes smooth follow stutter.

Implementation & operation cost: Two small conversion functions and a range calculation per frame; the real cost is discipline about which space every value lives in.

01

Three coordinate spaces, owned by two types

Tile coordinates are integer column and row indexes into the map. World coordinates are continuous positions in world pixels: with 16-pixel tiles, tile (c, r) covers x from c*16 up to, but not including, (c+1)*16. Screen coordinates are what the window shows after the camera offset and zoom. The map owns the tile-to-world rule and the camera owns the world-to-screen rule; no other code should do either conversion by hand. Simulation, collision and pathfinding stay in world or tile space. Screen space appears only at the two boundaries where the player meets the game: drawing, and turning a mouse or touch position back into a world point. Store each cell as a small index into a shared tileset rather than as an object with its own image. That is the flyweight pattern: a 40x30 map becomes 1200 bytes instead of 1200 sprite objects, and the tileset is loaded once.

02

Follow, clamp and cull with one camera value

The program builds a 40x30 map of 16-pixel tiles and shows it through a 640x360 window at zoom 2, which is a 320x180 view in world pixels. It moves the target to the top-left corner, the middle and the bottom-right corner and prints where the camera settled and which tiles intersect the view. It then sends a click through the inverse transform, centers a room smaller than the view, and shows what integer conversion does to a click in the margin beside that room.

go
package main

import (
	"fmt"
	"math"
)

const tileSize = 16

type Vec struct{ X, Y float64 }

// TileMap stores one tileset index per cell, row by row.
type TileMap struct {
	Cols, Rows int
	Tiles      []uint8
}

func (m TileMap) Size() Vec {
	return Vec{float64(m.Cols * tileSize), float64(m.Rows * tileSize)}
}

// Camera.Pos is the world position of the top-left screen pixel.
type Camera struct {
	Pos              Vec
	ScreenW, ScreenH float64
	Zoom             float64
}

func (c Camera) View() Vec { return Vec{c.ScreenW / c.Zoom, c.ScreenH / c.Zoom} }

func (c Camera) WorldToScreen(p Vec) Vec {
	return Vec{(p.X - c.Pos.X) * c.Zoom, (p.Y - c.Pos.Y) * c.Zoom}
}

func (c Camera) ScreenToWorld(p Vec) Vec {
	return Vec{p.X/c.Zoom + c.Pos.X, p.Y/c.Zoom + c.Pos.Y}
}

// Follow centers the target, then keeps the view inside the map.
// A map smaller than the view is centered instead.
func (c *Camera) Follow(target Vec, m TileMap) {
	view, size := c.View(), m.Size()
	c.Pos.X = clampAxis(target.X-view.X/2, size.X-view.X)
	c.Pos.Y = clampAxis(target.Y-view.Y/2, size.Y-view.Y)
}

func clampAxis(v, limit float64) float64 {
	if limit < 0 {
		return limit / 2
	}
	return min(max(v, 0), limit)
}

func worldToTile(p Vec) (col, row int) {
	return int(math.Floor(p.X / tileSize)), int(math.Floor(p.Y / tileSize))
}

type TileRange struct{ MinCol, MaxCol, MinRow, MaxRow int }

// Visible returns the inclusive tile range that touches the view.
func (c Camera) Visible(m TileMap) TileRange {
	view := c.View()
	minCol, minRow := worldToTile(c.Pos)
	maxCol := int(math.Ceil((c.Pos.X+view.X)/tileSize)) - 1
	maxRow := int(math.Ceil((c.Pos.Y+view.Y)/tileSize)) - 1
	return TileRange{
		MinCol: max(minCol, 0), MaxCol: min(maxCol, m.Cols-1),
		MinRow: max(minRow, 0), MaxRow: min(maxRow, m.Rows-1),
	}
}

func (r TileRange) Count() int { return (r.MaxCol - r.MinCol + 1) * (r.MaxRow - r.MinRow + 1) }

func main() {
	level := TileMap{Cols: 40, Rows: 30, Tiles: make([]uint8, 40*30)}
	cam := Camera{ScreenW: 640, ScreenH: 360, Zoom: 2}
	fmt.Printf("map %.0fx%.0f px, view %.0fx%.0f px at zoom %.0f\n",
		level.Size().X, level.Size().Y, cam.View().X, cam.View().Y, cam.Zoom)

	for _, target := range []Vec{{40, 30}, {300, 250}, {630, 470}} {
		cam.Follow(target, level)
		r := cam.Visible(level)
		fmt.Printf("target (%.0f,%.0f) camera (%.0f,%.0f) cols %d-%d rows %d-%d draw %d of %d\n",
			target.X, target.Y, cam.Pos.X, cam.Pos.Y,
			r.MinCol, r.MaxCol, r.MinRow, r.MaxRow, r.Count(), level.Cols*level.Rows)
	}

	click := Vec{100, 50}
	world := cam.ScreenToWorld(click)
	col, row := worldToTile(world)
	back := cam.WorldToScreen(world)
	fmt.Printf("click (%.0f,%.0f) -> world (%.0f,%.0f) -> tile (%d,%d) -> screen (%.0f,%.0f)\n",
		click.X, click.Y, world.X, world.Y, col, row, back.X, back.Y)

	room := TileMap{Cols: 12, Rows: 8, Tiles: make([]uint8, 12*8)}
	cam.Follow(Vec{96, 64}, room)
	r := cam.Visible(room)
	fmt.Printf("small room: camera (%.0f,%.0f) cols %d-%d rows %d-%d\n",
		cam.Pos.X, cam.Pos.Y, r.MinCol, r.MaxCol, r.MinRow, r.MaxRow)

	margin := cam.ScreenToWorld(Vec{110, 40})
	col, row = worldToTile(margin)
	fmt.Printf("margin click world (%.0f,%.0f): int() says (%d,%d), floor says (%d,%d)\n",
		margin.X, margin.Y, int(margin.X/tileSize), int(margin.Y/tileSize), col, row)
}
Read the code

Follow first centers the target (target minus half the view) and then clamps each axis to the range from 0 to mapSize - viewSize, so the corner targets print camera (0,0) and (320,300) instead of showing empty space past the edge. When the map is smaller than the view the limit is negative, and clampAxis returns half of it, which centers the 192x128 room at (-64,-26). Visible floors the top-left corner, takes ceil(edge / tileSize) - 1 for the bottom-right corner and clamps both to the map. A camera at x=140 therefore draws columns 8 to 28: 21 columns, one more than an aligned view, because partial tiles show at both edges. ScreenToWorld divides by the zoom and adds the camera position; WorldToScreen undoes it exactly, which the click line proves by returning to (100,50). The last line is the bug the next section explains.

03

Floor at the edges, and snap only when drawing

Go's conversion from float to int truncates toward zero, so int(-9.0/16) is 0, not -1. A click in the margin left of a centered room becomes a click on tile (0,0), and an entity standing just west of a chunk boundary is filed under the wrong chunk. math.Floor returns -1, which the bounds check then rejects. The same off-by-one hides at the far edge: a 320-pixel view starting at x=8 touches 21 columns, not 20, and a range computed as start + view / tileSize leaves a strip of unpainted background on the right. Clamping the range to the map is what makes culling safe as well as cheap: the draw loop can index the tile slice directly, because Visible never returns a column outside 0 to Cols-1, whatever the camera does. Keep the camera position as float64 in the simulation so smooth follow and screen shake stay smooth, and round it only at draw time. Pixel art drawn at fractional offsets shimmers and opens one-pixel seams between tiles; snapping the camera, not each tile, keeps neighbors exactly one tile apart.

04

Draw the visible range in Ebitengine

In a real game the same Camera drives Draw. Ebitengine scales the logical screen size returned by Layout to the window, and each DrawImage call takes a GeoM matrix. Translate by the tile position minus the snapped camera, then scale by the zoom. GeoM applies operations in the order you call them, so this is exactly WorldToScreen from the program.

go
func (g *Game) Layout(outsideW, outsideH int) (int, int) { return 640, 360 }

func (g *Game) Draw(screen *ebiten.Image) {
	r := g.cam.Visible(g.level)
	camX, camY := math.Floor(g.cam.Pos.X), math.Floor(g.cam.Pos.Y)
	op := &ebiten.DrawImageOptions{}
	for row := r.MinRow; row <= r.MaxRow; row++ {
		for col := r.MinCol; col <= r.MaxCol; col++ {
			op.GeoM.Reset()
			op.GeoM.Translate(float64(col*tileSize)-camX, float64(row*tileSize)-camY)
			op.GeoM.Scale(g.cam.Zoom, g.cam.Zoom)
			screen.DrawImage(g.tiles[g.level.Tiles[row*g.level.Cols+col]], op)
		}
	}
}
Read the code

This fragment needs github.com/hajimehoshi/ebiten/v2 and runs in your own native environment, not in the app. g.tiles holds sub-images cut once from a single tileset image with SubImage at load time, so consecutive draws share one source texture and Ebitengine can merge them into fewer GPU draw calls. One DrawImageOptions value is reset and reused for the whole loop instead of being allocated per tile; the frame-budget lesson measures why that matters. Flooring the camera to whole world pixels means that at zoom 2 every tile lands on an even screen pixel.

05

Camera behavior players notice, and how to test it

A camera locked rigidly to the player feels twitchy. Common refinements are a dead zone (move the camera only when the target leaves a central rectangle), look-ahead (offset toward the facing or velocity direction) and smoothing (move a fraction of the remaining distance each tick, which the tweening lesson builds properly). Apply all of them before the clamp so no refinement can push the view past the map edge. Parallax background layers reuse the same camera with its position multiplied by a factor below 1. Large worlds split the map into chunks and cull chunks first, then tiles inside each visible chunk, with the same floor-based range math. Test the camera as a table: targets at all four corners and the center, a map smaller than the view on one axis only, zoom 1, 2 and a fractional zoom such as 1.5, and a property check that every screen pixel converts back to a world point inside the reported tile range.

TAKE THIS WITH YOU

Keep the simulation in world space, convert through one camera type, floor (never truncate) from world to tile coordinates, clamp the camera before drawing and clamp the visible range so culling can never index outside the map.

Check your understanding

A click lands at world x = -9, in the margin left of the map. Why does int(x / 16) report the wrong tile?

Go to the source

Progress stays in this browser. No account needed.