Worlds, AI and multiplayer · 5 MIN READ
Tweens and sprite frames advance with the simulation tick, not the wall clock
Drive easing curves, chained and retargeted tweens and sprite animation clips from tick counts so motion is deterministic, pausable and free of jumps.
A panel slides in, a coin bounces, a character cycles through four walking frames. The tempting implementation reads time.Now in Draw and computes progress from it. That ties animation to the wall clock: it keeps running while the game is paused, it behaves differently at 60 Hz and 144 Hz, and a replay cannot reproduce it. The fixed-timestep loop from the previous unit already provides a better clock: the tick.
gamedev · A MAP OF THE IDEA
- Store from, to, duration
- Step once per tick
- Value from elapsed/total
- Retarget on interrupt
Useful when
- Pause, slow motion and replays work without special cases.
- Values land exactly on the target; nothing drifts.
Watch out
- Wall-clock animation diverges from the simulation and replays.
- Pointer targets outlive destroyed entities; use IDs.
Implementation & operation cost: A few small structs and pure easing functions; motion granularity is one tick unless Draw interpolates between ticks.
A tween is data: from, to, duration and elapsed ticks
Model a tween as a value holding a start, an end, a duration in ticks, the elapsed tick count and an easing function. Update calls Step once per tick and Draw reads Value. Because Value is computed from elapsed / duration instead of adding a small delta every tick, it cannot accumulate rounding error, and the last tick lands exactly on the target. Pausing means not calling Step, slow motion means stepping every other tick, and a replay reproduces every intermediate value. An easing function maps linear progress t from 0 to 1 onto eased progress with f(0) = 0 and f(1) = 1. It changes when the motion happens, not where it ends. Some easings leave the 0 to 1 range on purpose: outBack overshoots to give a panel a small bounce before it settles.
Ease, chain, retarget and animate in one program
The program samples four easings over a 10-tick tween, plays a two-step chain, cancels a slide partway through and compares a naive restart with a retarget, and finally picks sprite frames for a looping walk clip and a one-shot attack clip at selected ticks. Every value prints with fixed precision, so the output is identical on every platform.
package main
import (
"fmt"
"strings"
)
// An Ease maps progress t in [0,1] to eased progress; f(0)=0 and f(1)=1.
type Ease func(t float64) float64
func Linear(t float64) float64 { return t }
func OutCubic(t float64) float64 {
u := 1 - t
return 1 - u*u*u
}
func InOutQuad(t float64) float64 {
if t < 0.5 {
return 2 * t * t
}
u := 2 - 2*t
return 1 - u*u/2
}
// OutBack overshoots past 1 before settling, like a panel that bounces.
func OutBack(t float64) float64 {
const c1 = 1.70158
u := t - 1
return 1 + u*u*((c1+1)*u+c1)
}
// Tween is plain data advanced once per simulation tick.
type Tween struct {
From, To float64
Duration int // in ticks
Elapsed int
Ease Ease
}
func (tw *Tween) Step() {
if tw.Elapsed < tw.Duration {
tw.Elapsed++
}
}
func (tw Tween) Done() bool { return tw.Elapsed >= tw.Duration }
// Value is computed from Elapsed, so it never accumulates rounding drift.
func (tw Tween) Value() float64 {
if tw.Duration <= 0 {
return tw.To
}
t := float64(tw.Elapsed) / float64(tw.Duration)
return tw.From + (tw.To-tw.From)*tw.Ease(t)
}
// Retarget starts a new tween from wherever the old one is now.
func Retarget(cur Tween, to float64, ticks int, ease Ease) Tween {
return Tween{From: cur.Value(), To: to, Duration: ticks, Ease: ease}
}
// Chain plays tweens back to back; each starts where the previous ended.
type Chain struct {
Steps []Tween
index int
}
func (c *Chain) Step() {
if c.Steps[c.index].Done() && c.index < len(c.Steps)-1 {
c.index++
}
c.Steps[c.index].Step()
}
func (c *Chain) Value() float64 { return c.Steps[c.index].Value() }
func (c *Chain) Done() bool { return c.index == len(c.Steps)-1 && c.Steps[c.index].Done() }
// Clip picks a sprite frame from the ticks elapsed since the clip started.
type Clip struct {
Frames []int // indexes into a sprite sheet
TicksPerFrame int
Loop bool
}
func (c Clip) Frame(elapsed int) int {
i := elapsed / c.TicksPerFrame
if c.Loop {
i %= len(c.Frames)
} else {
i = min(i, len(c.Frames)-1)
}
return c.Frames[i]
}
func (c Clip) Finished(elapsed int) bool {
return !c.Loop && elapsed >= len(c.Frames)*c.TicksPerFrame
}
func main() {
eases := []struct {
name string
f Ease
}{{"linear", Linear}, {"outCubic", OutCubic}, {"inOutQuad", InOutQuad}, {"outBack", OutBack}}
fmt.Printf("%4s %9s %9s %9s %9s\n", "tick", "linear", "outCubic", "inOutQuad", "outBack")
for tick := 0; tick <= 10; tick += 2 {
row := []string{fmt.Sprintf("%4d", tick)}
for _, e := range eases {
tw := Tween{From: 0, To: 1, Duration: 10, Elapsed: tick, Ease: e.f}
row = append(row, fmt.Sprintf("%9.3f", tw.Value()))
}
fmt.Println(strings.Join(row, " "))
}
chain := Chain{Steps: []Tween{
{From: 0, To: 100, Duration: 4, Ease: OutCubic},
{From: 100, To: 40, Duration: 3, Ease: InOutQuad},
}}
samples := []string{fmt.Sprintf("%.1f", chain.Value())}
for !chain.Done() {
chain.Step()
samples = append(samples, fmt.Sprintf("%.1f", chain.Value()))
}
fmt.Println("chain:", strings.Join(samples, " "))
slide := Tween{From: 0, To: 100, Duration: 8, Ease: Linear}
for range 3 {
slide.Step()
}
naive := Tween{From: 100, To: 0, Duration: 4, Ease: Linear}
naive.Step()
fmt.Printf("cancel at %.1f: naive restart jumps to %.1f\n", slide.Value(), naive.Value())
back := Retarget(slide, 0, 4, Linear)
samples = samples[:0]
for !back.Done() {
back.Step()
samples = append(samples, fmt.Sprintf("%.1f", back.Value()))
}
fmt.Println("retarget from current value:", strings.Join(samples, " "))
walk := Clip{Frames: []int{4, 5, 6, 7}, TicksPerFrame: 6, Loop: true}
attack := Clip{Frames: []int{8, 9, 10}, TicksPerFrame: 4}
for _, c := range []struct {
name string
clip Clip
}{{"walk", walk}, {"attack", attack}} {
var frames []string
for _, t := range []int{0, 5, 6, 11, 12, 23, 24} {
frames = append(frames, fmt.Sprint(c.clip.Frame(t)))
}
fmt.Printf("%s frames at ticks 0 5 6 11 12 23 24: %s (finished at 24: %t)\n",
c.name, strings.Join(frames, " "), c.clip.Finished(24))
}
}The table shows the character of each curve: outCubic covers almost half the distance in the first fifth of the time, inOutQuad starts and ends slowly, and outBack peaks at 1.099 before settling at exactly 1.000. Chain advances the current tween and moves to the next one only after the current one reports Done, so 100.0 appears once and the second step starts from it: eight samples for 4 + 3 ticks. The cancelled slide is at 37.5 after three of eight ticks. Restarting a tween from the original end point jumps to 75.0 on the next tick, while Retarget starts from the current value and glides down to 0.0. Clip.Frame divides elapsed ticks by ticks per frame. The walk loop wraps with a modulo, so tick 24 shows frame 4 again; the one-shot attack clamps to its last frame and reports Finished at tick 24, which a state machine can use to leave the attack state.
Cancelling and chaining without visible jumps
Interruptions are where tweens go wrong. When a menu closes while it is still opening, there are three policies: hold (stop where it is), complete (jump to the end) and retarget (start a new tween from the current value toward the new target). Retarget is almost always what players expect; jumping to an end point first is the visible snap the program prints. Make the policy explicit in the API instead of letting each caller overwrite fields. Chains need a rule for the boundary tick: show either the last value of one tween or the first value of the next, never both and never neither. Completion callbacks are convenient, but a callback that starts another tween on the same object while the chain is still iterating is a classic source of skipped steps; prefer reporting Done and letting the owner decide. Refer to tween targets by entity ID resolved each tick, not by pointer, so a tween whose entity was destroyed finds nothing and ends instead of writing into a recycled slot.
Sprite frames are a function of elapsed ticks
A clip is a list of sprite-sheet indexes and a ticks-per-frame rate. The current frame is computed from the ticks since the clip started, so an entity stores only the clip and its start tick, not a frame counter that must be incremented and reset correctly. Switching from walk to attack records a new start tick; switching to the clip that is already playing must not, or a held key restarts the walk cycle on every tick. Gameplay events tied to animation, such as the frame where a sword connects, belong in the simulation as tick offsets within the clip, not in Draw, so they happen on the same tick in a replay and on a server. In Ebitengine, Update runs at the tick rate (60 per second unless SetTPS changes it) while Draw can run at the display rate. That is the right split: step tweens and clips in Update, read them in Draw, and interpolate between the previous and current tick with the fixed-timestep alpha if motion looks steppy on fast displays.
Test animation as a table of samples
Because every value is a function of the tick, tests need no timers and no sleeps. Assert f(0) = 0 and f(1) = 1 for each easing, compare curves at fixed ticks against golden values formatted to three decimals like the table above, and check monotonicity wherever a curve promises it. Cover the edges: a zero-duration tween reports its target immediately, stepping past the end stays at the end, a retarget never moves the value on the retarget tick itself, and a one-shot clip with a single frame finishes after exactly its ticks-per-frame. If designers tune durations in seconds, convert them to ticks once at load time with an explicit rounding rule and test that the conversion is stable for your tick rate.
TAKE THIS WITH YOU
Advance tweens and sprite clips by simulation ticks, compute values from elapsed ticks instead of accumulating deltas, retarget from the current value when interrupted, and keep animation-driven gameplay events in Update.
Check your understanding
A menu is closed while its opening animation is halfway done. Which approach avoids a visible jump?
Go to the source
Progress stays in this browser. No account needed.