Game loop, input and physics · 5 MIN READ

A 2D vector value type: normalized input, acceleration and drag in per-tick units

Write a small value-semantics vector type and move a body with normalized input, per-tick acceleration and drag that behave the same on every display.

Almost every line of 2D movement code adds, scales or measures a pair of numbers. A tiny vector type with value methods makes that code read like the math, rules out aliasing bugs and costs nothing measurable. Combined with fixed ticks, it lets you tune movement in units a designer can reason about: pixels per tick, and a drag factor applied once per tick.

gamedev · A MAP OF THE IDEA

  1. Read raw direction
  2. Normalize to unit length
  3. Accelerate, then drag
  4. Add velocity to position

Useful when

  • Value methods chain cleanly and cannot alias shared state.
  • Per-tick constants give identical movement on every display.

Watch out

  • Changing TPS means converting every tuning constant.
  • Float results can differ across architectures through FMA fusion.

Implementation & operation cost: A thirty-line type and the habit of thinking in ticks; lockstep multiplayer may additionally need fixed-point math.

01

Value methods for a two-float type

Vec2 is two float64 fields, small enough that copying it is cheap and usually stays in registers, and a copy can never be changed behind your back. Every method takes a Vec2 and returns a new one: a.Add(b) leaves a untouched, so b.Vel.Add(...).Scale(drag) reads as one expression without temporaries. Value semantics also make the zero value meaningful: Vec2{} is the origin and a valid 'no direction'. Length uses math.Hypot, which avoids needless overflow and underflow in the intermediate squares; when you only need to compare distances, compare squared lengths instead, as the collision lesson does. Do not use float vectors as map keys: two positions that print identically can differ in the last bit.

02

Normalize diagonal input, then integrate per tick

Holding right and down produces the raw direction (1, 1), whose length is about 1.41. Scaling that by an acceleration makes diagonal movement 41% faster than straight movement, a bug players notice within seconds. Normalize rescales the direction to length 1 and returns the zero vector when nothing is held, instead of dividing by zero and producing NaN. Each tick the body then adds normalized input times accel to its velocity, multiplies velocity by drag, snaps tiny speeds to zero and adds velocity to position. Updating velocity before position is semi-implicit Euler integration: as cheap as the naive order and much more stable for game physics.

go
package main

import (
	"fmt"
	"math"
)

// Vec2 is small and immutable in use: every method takes and returns values.
type Vec2 struct{ X, Y float64 }

func (a Vec2) Add(b Vec2) Vec2      { return Vec2{a.X + b.X, a.Y + b.Y} }
func (a Vec2) Scale(k float64) Vec2 { return Vec2{a.X * k, a.Y * k} }
func (a Vec2) Len() float64         { return math.Hypot(a.X, a.Y) }

// Normalize returns a unit vector, or the zero vector when there is no direction.
func (a Vec2) Normalize() Vec2 {
	l := a.Len()
	if l == 0 {
		return Vec2{}
	}
	return a.Scale(1 / l)
}

func (a Vec2) String() string { return fmt.Sprintf("(%.2f, %.2f)", a.X, a.Y) }

// Tuning values are per tick at a fixed 60 ticks per second.
const (
	tps       = 60
	accel     = 0.6  // px/tick gained per tick while input is held
	drag      = 0.8  // velocity multiplier applied every tick
	stopBelow = 0.05 // px per tick; snap tiny speeds to zero
)

type Body struct{ Pos, Vel Vec2 }

func (b *Body) Step(input Vec2) {
	b.Vel = b.Vel.Add(input.Normalize().Scale(accel)).Scale(drag)
	if b.Vel.Len() < stopBelow {
		b.Vel = Vec2{}
	}
	b.Pos = b.Pos.Add(b.Vel) // semi-implicit Euler: new velocity, then position
}

func main() {
	raw := Vec2{1, 1} // right + down held together
	fmt.Printf("raw input %v length %.2f\n", raw, raw.Len())
	fmt.Printf("unit dir  %v length %.2f\n", raw.Normalize(), raw.Normalize().Len())

	var b Body
	for tick := 1; tick <= 60; tick++ {
		input := Vec2{}
		if tick <= 12 {
			input = raw
		}
		b.Step(input)
		stopped := tick > 12 && b.Vel == (Vec2{})
		if tick <= 3 || tick == 12 || tick == 13 || tick == 20 || stopped {
			fmt.Printf("tick %2d pos=%v speed=%.3f px/tick\n", tick, b.Pos, b.Vel.Len())
		}
		if stopped {
			break
		}
	}
	terminal := accel * drag / (1 - drag)
	fmt.Printf("terminal speed %.2f px/tick = %.0f px/s at %d TPS\n", terminal, terminal*tps, tps)
	fmt.Printf("without Normalize the diagonal tops out at %.2f px/tick\n", terminal*raw.Len())
}
Read the code

The first two lines show the raw diagonal and its unit direction. While input is held (ticks 1 to 12), speed climbs 0.480, 0.864, 1.171 and approaches the terminal speed where the gain of 0.6 per tick balances the 20% drag: v = (v + 0.6) * 0.8 solves to 2.40 px/tick. After release, speed shrinks by a factor of 0.8 per tick until it drops below 0.05 and snaps to zero on tick 30, so the body stops for good instead of creeping by ever smaller amounts. The last line shows what skipping Normalize costs: a diagonal top speed of 3.39 instead of 2.40.

03

Why per-tick units beat per-frame units

With a fixed tick rate, a speed of 2.4 px/tick is exact and the same on every machine, because the fixed-timestep lesson guarantees how many ticks run per second. Per-frame units are wrong on every display except the one you tuned on. Per-second units multiplied by dt are correct in principle but bury the step size in every formula, and drag does not scale linearly: a factor of 0.8 per tick is 0.8 to the power 60 per second, not 0.8 times 60. Keep tuning constants per tick, convert only for people (2.40 px/tick is 144 px/s at 60 TPS), and if you ever change TPS, convert every constant deliberately.

go
// Convert per-tick tuning from 60 to 120 ticks per second.
ratio := 60.0 / 120.0
speed120 := speed60 * ratio         // px/tick halves
accel120 := accel60 * ratio * ratio // px/tick gained per tick quarters
drag120 := math.Pow(drag60, ratio)  // 0.8 becomes about 0.894
Read the code

This fragment shows the arithmetic and is not a runnable program. Doubling TPS halves the distance per tick, quarters the velocity gained per tick, and turns the drag factor into its square root, so two new ticks remove as much speed as one old tick did. Missing any of these changes how the game feels, which is why the tick rate should be chosen once and early.

04

Floating point is reproducible only within one build

The output above is exact for this toolchain and machine, but floating-point results are not guaranteed to be bit-identical across architectures. The Go specification allows an implementation to fuse x*y + z into a single fused multiply-add, which skips one rounding, and whether that happens depends on the target architecture and its settings, so the same source can differ in the last bit and drift apart after thousands of ticks. That never matters for a single-player game printed at two decimals. It matters for lockstep multiplayer and for replays shared between platforms. An explicit conversion forces the intermediate rounding and forbids fusion; teams that need strict cross-platform determinism often go further and keep positions in fixed-point integers, as the integer jump physics in the input lesson does.

go
// The compiler may fuse this into one multiply-add on some targets:
next := pos + vel*dt
// The explicit conversion forces vel*dt to be rounded first, forbidding fusion:
next = pos + float64(vel*dt)
Read the code

This fragment follows the floating-point operator rules in the Go specification. In the first line the product veldt is not explicitly rounded, so the compiler may compute pos + veldt as one fused operation. Wrapping the product in float64(...) requires it to be rounded to float64 first, which makes the result the same with or without FMA hardware.

05

Test movement as a pure function

Movement is a pure function of state and input, so table tests pin it down cheaply. Assert that a held diagonal reaches the same top speed as a held cardinal direction, that releasing input reaches exactly zero within a known number of ticks, and that normalizing the zero vector returns the zero vector rather than NaN. NaN is contagious: one bad division turns a position into NaN, every comparison against it is false, and collision code silently stops working, so a debug assertion with math.IsNaN in the step function pays for itself. Keep a body's state in one struct and step it from one place; a second code path that nudges position directly, such as knockback applied from an animation callback, is how determinism quietly breaks.

TAKE THIS WITH YOU

Use a small value-type vector, normalize the input direction before scaling it, update velocity and then position once per tick, and keep every tuning constant per tick so movement is identical wherever the same build runs.

Check your understanding

Holding right and down adds (1, 1) times the acceleration to velocity. What goes wrong without normalizing?

Go to the source

Progress stays in this browser. No account needed.