Game loop, input and physics · 6 MIN READ

Ebitengine's Game interface: Update advances ticks, Draw only reads, Layout fixes the screen

Structure an Ebitengine game so every state change happens in Update, Draw is a read-only view, and the rules run headless in tests.

Ebitengine runs the loop from the previous lesson for you. You implement three methods, Update, Draw and Layout, and the engine decides when to call each one. Getting that split right is the most important structural decision in an Ebitengine project: a single state change inside Draw makes the game run at a different speed on every monitor.

gamedev · A MAP OF THE IDEA

  1. Layout sets logical size
  2. Update advances one tick
  3. Draw renders current state
  4. Return Termination to quit

Useful when

  • Game speed is identical on every display refresh rate.
  • Rules behind a plain Step function run headless in tests.

Watch out

  • Any state change in Draw becomes a frame-rate bug.
  • Draw gets no interpolation factor; smooth high-refresh motion needs extra work.

Implementation & operation cost: A strict split between Update and Draw plus a thin input adapter; little code, but the rule has to be enforced in review.

01

Three methods on two different clocks

ebiten.Game is an interface with three methods: Update() error, Draw(screen *ebiten.Image) and Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int). Update runs at a fixed tick rate, 60 ticks per second by default and adjustable with ebiten.SetTPS, and the documentation lets you treat the time between two Updates as exactly 1/TPS seconds, so you never measure time inside it. Draw runs once per rendered frame, and how often that happens depends on the display: on a 120 Hz monitor there are about two Draw calls per Update, and when frames are slow the engine may run several Updates before the next Draw. Layout receives the outside size of the window or screen and returns the logical screen size; Ebitengine scales the logical screen to fit, so returning a fixed 320 by 180 gives a pixel-art canvas at any window size. In the first frame Update is guaranteed to run at least once before Draw, so Update is also the natural place for lazy initialization.

02

A headless driver shows why logic belongs in Update

The Ebitengine module is not available in this sandbox, so the program declares a Game interface with the same three methods and a Screen type that stands in for *ebiten.Image. The run function plays the engine: each frame it calls Layout, then Update as many times as the schedule says, then Draw once. Three schedules model the same 100 ms on a 60 Hz, a 120 Hz and a 30 Hz display. Drone moves in Update; DrawDrone moves in Draw. The last two runs exercise the three possible results of Update: nil continues, the Termination sentinel stops cleanly, and any other error stops the game and is returned to the caller.

go
package main

import (
	"errors"
	"fmt"
)

// Screen stands in for *ebiten.Image: Draw writes to it and nothing else.
type Screen struct {
	W, H int
	Text string
}

// Game has the same three methods as ebiten.Game, with the headless Screen.
type Game interface {
	Update() error
	Draw(screen *Screen)
	Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int)
}

// Termination plays the role of ebiten.Termination: stop without an error.
var Termination = errors.New("regular termination")

// Drone changes state only in Update, one tick at a time.
type Drone struct {
	Tick, X, Goal int
}

func (d *Drone) Update() error {
	d.Tick++
	d.X += 2
	if d.Goal > 0 && d.X >= d.Goal {
		return Termination
	}
	return nil
}

func (d *Drone) Draw(s *Screen) { s.Text = fmt.Sprintf("tick=%d x=%d", d.Tick, d.X) }

func (d *Drone) Layout(outsideWidth, outsideHeight int) (int, int) { return 320, 180 }

// DrawDrone moves inside Draw, so its speed follows the display.
type DrawDrone struct{ Drone }

func (d *DrawDrone) Update() error { d.Tick++; return nil }

func (d *DrawDrone) Draw(s *Screen) {
	d.X += 2
	d.Drone.Draw(s)
}

var errDiskFull = errors.New("disk full")

// Saver fails on its third tick, the way a real I/O error would surface.
type Saver struct{ Drone }

func (s *Saver) Update() error {
	s.Tick++
	if s.Tick == 3 {
		return fmt.Errorf("autosave: %w", errDiskFull)
	}
	return nil
}

// run is a headless stand-in for ebiten.RunGame. Each schedule entry is one
// frame: Layout, then that many Update calls, then one Draw.
func run(g Game, schedule []int) (frames, ticks int, screen Screen, err error) {
	for _, updates := range schedule {
		screen.W, screen.H = g.Layout(1920, 1080)
		for range updates {
			ticks++
			if err := g.Update(); err != nil {
				if errors.Is(err, Termination) {
					return frames, ticks, screen, nil
				}
				return frames, ticks, screen, err
			}
		}
		g.Draw(&screen)
		frames++
	}
	return frames, ticks, screen, nil
}

func repeat(pattern []int, times int) []int {
	var out []int
	for range times {
		out = append(out, pattern...)
	}
	return out
}

func main() {
	displays := []struct {
		name     string
		schedule []int
	}{
		{"60 Hz", repeat([]int{1}, 6)},
		{"120 Hz", repeat([]int{1, 0}, 6)},
		{"30 Hz", repeat([]int{2}, 3)},
	}
	for _, d := range displays {
		frames, ticks, screen, _ := run(&Drone{}, d.schedule)
		_, _, drawn, _ := run(&DrawDrone{}, d.schedule)
		fmt.Printf("%-6s %2d frames, %d ticks: Update-driven %q, Draw-driven %q\n",
			d.name, frames, ticks, screen.Text, drawn.Text)
	}
	_, ticks, screen, err := run(&Drone{Goal: 20}, repeat([]int{1}, 60))
	fmt.Printf("goal: Termination on tick %d, last frame %q at %dx%d, err=%v\n",
		ticks, screen.Text, screen.W, screen.H, err)
	_, ticks, _, err = run(&Saver{}, repeat([]int{1}, 60))
	fmt.Printf("saver: stopped on tick %d, err=%v, disk full=%t\n", ticks, err, errors.Is(err, errDiskFull))
}
Read the code

Every display delivers six ticks, so Drone ends at x=12 each time although Draw ran 6, 12 or 3 times. DrawDrone moves 2 units per Draw and ends at 12, 24 and 6: on the 120 Hz display it literally runs twice as fast. The goal run returns Termination from its tenth Update; run maps it to a nil error the way ebiten.RunGame does, and the last drawn frame shows tick 9 because in this model the terminating tick is never drawn. Saver wraps a sentinel with %w, so the caller can still match it with errors.Is after the game stops.

03

The real main, as a fragment

In your own module the same structure hosts on Ebitengine with a handful of calls. ebiten.RunGame blocks until the game ends and returns the error Update returned, or nil after ebiten.Termination. Window size and title are set before RunGame. Images are allocated once, outside Draw: creating an *ebiten.Image every frame puts texture allocation on the hottest path in the program. Draw positions the sprite through DrawImageOptions.GeoM, the transform applied while the source image is drawn onto the screen, and ebitenutil.DebugPrint writes a line of debug text in the corner.

go
import (
	"fmt"
	"image/color"
	"log"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/ebitenutil"
)

type Game struct {
	tick   int
	x      float64
	sprite *ebiten.Image // created once in main, never inside Draw
}

var _ ebiten.Game = (*Game)(nil)

func (g *Game) Update() error {
	if ebiten.IsKeyPressed(ebiten.KeyEscape) {
		return ebiten.Termination // RunGame returns nil
	}
	g.tick++
	g.x += 2
	if g.x > 320 {
		g.x = -16
	}
	return nil
}

func (g *Game) Draw(screen *ebiten.Image) {
	screen.Fill(color.RGBA{0x10, 0x18, 0x20, 0xff})
	op := &ebiten.DrawImageOptions{}
	op.GeoM.Translate(g.x, 82)
	screen.DrawImage(g.sprite, op)
	ebitenutil.DebugPrint(screen, fmt.Sprintf("tick %d", g.tick))
}

func (g *Game) Layout(outsideWidth, outsideHeight int) (int, int) {
	return 320, 180 // logical pixels; Ebitengine scales them to the window
}

func main() {
	sprite := ebiten.NewImage(16, 16)
	sprite.Fill(color.RGBA{0x00, 0xad, 0xd8, 0xff})
	ebiten.SetWindowSize(960, 540)
	ebiten.SetWindowTitle("Drone")
	if err := ebiten.RunGame(&Game{sprite: sprite}); err != nil {
		log.Fatal(err)
	}
}
Read the code

Run this fragment in your own environment after adding github.com/hajimehoshi/ebiten/v2 to a module; it is not compiled here and its package clause is omitted. The var _ line proves at compile time that *Game satisfies ebiten.Game. Update returns ebiten.Termination when Escape is held, so RunGame returns nil, while a genuine failure would come back as an error and reach log.Fatal. Draw only reads g.x and g.tick, so it is correct no matter how many times per tick the engine calls it.

04

Keep engine calls at the edge of Update

Update is the only method that changes state, but the rules do not have to live in it. A thin Update that copies Ebitengine input into a plain struct and calls world.Step(input) keeps the rules in code that never imports the engine: tests call Step with scripted input thousands of times per second, a replay system feeds recorded input, and a server can run the same Step without a window. Draw follows the mirror rule: it reads the world and issues draw calls, but never advances timers, consumes input or spawns particles, because the number of Draw calls per tick varies. Animation is the usual slip: derive the frame from the tick counter instead of incrementing a counter in Draw.

go
func (g *Game) Update() error {
	in := Input{
		Left:  ebiten.IsKeyPressed(ebiten.KeyArrowLeft),
		Right: ebiten.IsKeyPressed(ebiten.KeyArrowRight),
	}
	return g.world.Step(in) // plain Go below this line: no ebiten imports
}

func (g *Game) Draw(screen *ebiten.Image) {
	frame := g.world.Tick / 8 % 4 // animation derived from ticks, not counted here
	g.drawPlayer(screen, frame)
}
Read the code

This fragment belongs to the same program as the RunGame fragment and runs in your own environment. Input is a plain struct and world.Step is ordinary Go, so a test can build Input values directly. The animation frame is a pure function of world.Tick, so two Draw calls for the same tick show the same frame. The input lesson in this unit replaces the booleans with action bits and edge detection.

05

Ticks, frames and what to measure

Express every speed, cooldown and animation length in ticks and treat TPS as a design constant chosen once. ebiten.ActualTPS and ebiten.ActualFPS report measured rates for a debug overlay; game logic must not depend on them, because they fluctuate while the tick contract does not. Ebitengine does not hand Draw an interpolation factor, so at the default 60 TPS a 144 Hz display shows some ticks for two frames and others for three. Most 2D games accept that; a game that needs smoother motion can raise TPS or compute its own alpha from a monotonic clock as in the previous lesson. Passing ebiten.SyncWithFPS to SetTPS makes Update run once per frame, which brings back variable step lengths and every problem of the frame-sized loop. When you review an Ebitengine game, search Draw for assignments to game state: each one is a speed bug waiting for a faster monitor.

TAKE THIS WITH YOU

Change state only in Update and measure it in ticks; make Draw a read-only view that is safe to call any number of times; return ebiten.Termination to quit cleanly; keep the rules behind a plain Step function so they run headless.

Check your understanding

In an Ebitengine game, why must movement code live in Update rather than Draw?

Go to the source

Progress stays in this browser. No account needed.