Game loop, input and physics · 6 MIN READ
Input as actions: edge detection, jump buffering and coyote time in a tick-exact simulation
Map physical keys to actions, detect presses on the action level, and implement jump buffering and coyote time as tick counters that can be tested deterministically.
Players do not press buttons on the exact tick the game expects. They press jump a few ticks before landing or a few ticks after running off a ledge, and a strict implementation swallows those presses and feels broken. Responsive platformer controls are built from three small pieces: an action layer over physical keys, edge detection on actions, and short grace windows measured in ticks.
gamedev · A MAP OF THE IDEA
- Poll keys once per tick
- Map keys to action bits
- Edge = down &^ prev
- Apply grace windows
Useful when
- Rebinding and multiple devices become a data change.
- Forgiving controls are exact, replayable tick rules.
Watch out
- Per-key edges double-fire when two keys share an action.
- A tap shorter than one tick is invisible to polling.
Implementation & operation cost: A binding table, two bytes of action state and two counters per player; the real cost is play-testing the window sizes.
Bind keys to actions, then detect edges on actions
Game logic should ask whether Jump is pressed, never whether Space is. A binding table maps each physical key or button to an action, several keys may share one action (Space, W and a gamepad face button all mean Jump), and rebinding becomes a data change. Storing a tick's actions as bits in a uint8 makes the whole input state one comparable value: pressed is down&a != 0, and just pressed is down &^ prev, the bits set now that were clear on the previous tick. Detecting edges on actions rather than keys matters as soon as two keys share an action. A per-key helper such as Ebitengine's inpututil.IsKeyJustPressed correctly reports a fresh press when the player adds W while already holding Space; OR the per-key edges together and you get a second jump the player never asked for.
Simulate the controls tick by tick
The program drives a player through 75 scripted ticks: a long hold of Space, a second jump key pressed during that hold, a tap on the floor, a press shortly before landing, and a run to the right over two ledges with one press after each. The physics is integer arithmetic on purpose: gravity is 1 per tick and a jump sets the vertical speed to 5, so every tick is exact and the output reads as a precise specification of the controls. Only ticks with an event are printed.
package main
import "fmt"
// Key names a physical control; Ebitengine would use ebiten.Key values.
type Key string
// Action is a bit set, so one tick's input is a single comparable value.
type Action uint8
const (
Left Action = 1 << iota
Right
Jump
)
// bindings maps physical keys to actions; several keys may share an action.
var bindings = map[Key]Action{
"ArrowLeft": Left, "KeyA": Left,
"ArrowRight": Right, "KeyD": Right,
"Space": Jump, "KeyW": Jump, "PadSouth": Jump,
}
// Input holds this tick's actions and the previous tick's.
type Input struct{ down, prev Action }
func (in *Input) Poll(keys []Key) {
in.prev, in.down = in.down, 0
for _, k := range keys {
in.down |= bindings[k]
}
}
func (in Input) Pressed(a Action) bool { return in.down&a != 0 }
func (in Input) JustPressed(a Action) bool { return in.down&^in.prev&a != 0 }
const (
gravity = 1
jumpSpeed = 5
coyoteTicks = 4 // a jump is still allowed this many ticks after leaving the floor
bufferTicks = 5 // a jump press is remembered this many ticks
)
func floorAt(x int) int {
switch {
case x < 12:
return 0
case x < 30:
return -10
default:
return -100
}
}
type Player struct {
X, Y, VY int
air int // ticks since the feet last touched the floor
jumped bool // this airtime began with a jump, so coyote time is spent
press int // ticks since an unused jump press; -1 when none is pending
}
func (p *Player) Tick(in Input) (event string) {
if in.JustPressed(Jump) {
p.press = 0
if p.air > 0 {
event = fmt.Sprintf("jump pressed %d ticks off the floor", p.air)
}
}
if p.press >= 0 {
switch {
case !p.jumped && p.air <= coyoteTicks:
event = fmt.Sprintf("jump: pressed %d ticks ago, %d ticks off the floor", p.press, p.air)
p.VY, p.jumped, p.press = jumpSpeed, true, -1
case p.press >= bufferTicks:
event, p.press = "buffered press expired", -1
default:
p.press++
}
}
if in.Pressed(Right) {
p.X++
}
if in.Pressed(Left) {
p.X--
}
p.VY -= gravity
p.Y += p.VY
if f := floorAt(p.X); p.Y <= f {
if p.air > 0 && event == "" {
event = fmt.Sprintf("landed at x=%d y=%d", p.X, f)
}
p.Y, p.VY, p.air, p.jumped = f, 0, 0, false
} else {
p.air++
}
return event
}
type hold struct {
key Key
from, to int // inclusive ticks
}
func keysAt(script []hold, tick int) []Key {
var keys []Key
for _, h := range script {
if tick >= h.from && tick <= h.to {
keys = append(keys, h.key)
}
}
return keys
}
func main() {
script := []hold{
{"Space", 2, 14}, // hold through landing: one jump, not a bounce
{"KeyW", 6, 7}, // second jump key while Space is held: no new edge
{"Space", 17, 17}, // tap on the floor
{"PadSouth", 24, 24}, // pressed just before landing: buffered
{"KeyD", 30, 75}, // run right toward two ledges
{"Space", 43, 43}, // two ticks after walking off: coyote jump
{"Space", 65, 65}, // six ticks after the next ledge: too late
}
p := &Player{press: -1}
var in Input
keyEdges, actionEdges := 0, 0
held := map[Key]bool{}
for tick := 1; tick <= 75; tick++ {
keys := keysAt(script, tick)
now := map[Key]bool{}
for _, k := range keys {
if !held[k] && bindings[k] == Jump {
keyEdges++
}
now[k] = true
}
held = now
in.Poll(keys)
if in.JustPressed(Jump) {
actionEdges++
}
if ev := p.Tick(in); ev != "" {
fmt.Printf("tick %2d: %s\n", tick, ev)
}
}
fmt.Printf("jump keys went down %d times; the Jump action had %d edges\n", keyEdges, actionEdges)
}Tick 2 jumps from the floor. Space stays down until tick 14 and W joins it on tick 6, but the Jump action has no new edge, so the landing on tick 10 does not bounce. On tick 24 PadSouth is pressed seven ticks into the air; the press is buffered, the player lands on tick 25, and tick 26 jumps with a two-tick-old press. On tick 41 the player runs off the first ledge; the press on tick 43 comes two ticks after leaving the floor, inside the four-tick coyote window, so it jumps. After the second ledge the press comes six ticks late: no coyote time is left, the buffered press expires on tick 70, and the player lands on tick 71 without jumping. The summary counts six key presses but five action edges, because W never created one.
Buffering and coyote time are two counters
Both features are windows measured in ticks, and both live in Player, where tests can see them. Jump buffering forgives a press that is too early: press is set to 0 on the action edge, grows by one each tick it stays unused, and is cleared when it reaches bufferTicks while a jump is still impossible, so a press made up to five ticks before the first grounded tick still fires. Coyote time forgives a press that is too late: air counts ticks since the feet last touched the floor, and a jump is allowed while air is at most coyoteTicks. The jumped flag is the detail that is easy to miss. A jump also leaves the floor, and without the flag the coyote rule would allow a second jump during the first four ticks of the first one. Start with a handful of ticks for each window and tune them by playing; keep them in ticks for the reasons the movement lesson gives.
Wire the same logic to Ebitengine
In a real game, polling is the only code that touches the engine. It runs once per tick at the start of Update and turns key states into the Action bits the simulation already understands. Polling at the tick rate has one consequence worth knowing: a press and release that both happen between two polls are invisible, so an extremely short tap can be lost. At 60 TPS that window is about 17 ms and rarely matters. Ebitengine documents its Key constants as physical key positions on a US keyboard, so a WASD layout stays in the same place for players with other keyboard layouts; when a rebinding screen shows key names, remember that the label printed on the player's key may differ from the constant's name.
var jumpKeys = []ebiten.Key{ebiten.KeySpace, ebiten.KeyW, ebiten.KeyArrowUp}
func pollActions() Action {
var a Action
for _, k := range jumpKeys {
if ebiten.IsKeyPressed(k) {
a |= Jump
}
}
if ebiten.IsKeyPressed(ebiten.KeyArrowLeft) || ebiten.IsKeyPressed(ebiten.KeyA) {
a |= Left
}
if ebiten.IsKeyPressed(ebiten.KeyArrowRight) || ebiten.IsKeyPressed(ebiten.KeyD) {
a |= Right
}
return a
}
func (g *Game) Update() error {
g.in.prev, g.in.down = g.in.down, pollActions()
g.player.Tick(g.in)
return nil
}Run this fragment in your own Ebitengine module; it reuses Action, Input and Player from the program above. IsKeyPressed reports each key's level once per tick, and the edge is computed from the previous tick's Action bits, so W pressed while Space is held never produces a second Jump edge. Because Update runs at a fixed tick rate, bufferTicks and coyoteTicks mean the same amount of time on every display.
Test controls as tables of ticks
Input is a list of held keys per tick and the output is a list of events, so every control rule becomes a regression test: press three ticks before landing and expect a jump on the first grounded tick; press coyoteTicks + 1 ticks after a ledge and expect none; hold jump across a landing and expect exactly one jump. These tests catch the classic regressions, such as incrementing the buffer before the jump check, which silently shortens the window by a tick, or dropping the jumped flag, which turns coyote time into a double jump. Record real play sessions in the same format and a bug report becomes an exact replay. Combos and charge attacks extend the same idea: small counters over action edges, never timers that read the wall clock.
TAKE THIS WITH YOU
Read physical keys into action bits once per tick, detect edges on actions rather than keys, and express buffering and coyote time as tick counters in game state so every forgiving rule is deterministic and testable.
Check your understanding
A player runs off a ledge and presses jump two ticks later. Which mechanism lets that jump happen?
Go to the source
Progress stays in this browser. No account needed.