Tweening & Procedural Motion
Not everything that moves needs keyframes. A coin that pops up when collected, a door that slides open, a menu panel that drops in, a camera that glides to a new viewpoint: these are tweens, short animations from a start value to an end value over a fixed time with an easing curve. And bobbing pickups, swaying plants and springy cameras are procedural motion: a formula of time evaluated every frame. Together they add most of a game's "juice" at almost no cost.
Easing
A tween computes progress p = elapsed / duration (0 to 1) and passes it through an easing function before mixing the values: value = from + (to − from) · ease(p). The ease decides the character of the motion:
// Common easing functions, sampled at a few points. All map 0 -> 0 and 1 -> 1.
const ease = {
linear: (p) => p,
quadOut: (p) => 1 - (1 - p) * (1 - p), // fast start, gentle stop
cubicInOut: (p) => (p < 0.5 ? 4 * p ** 3 : 1 - (-2 * p + 2) ** 3 / 2),
backOut: (p) => { const c = 1.70158; return 1 + (c + 1) * (p - 1) ** 3 + c * (p - 1) ** 2; }, // overshoots
elasticOut: (p) => (p === 0 || p === 1 ? p : 2 ** (-10 * p) * Math.sin((p * 10 - 0.75) * (2 * Math.PI) / 3) + 1),
};
const ps = [0, 0.2, 0.4, 0.6, 0.8, 1];
console.log('p ' + ps.map((p) => p.toFixed(1).padStart(6)).join(''));
for (const [name, f] of Object.entries(ease)) {
console.log(name.padEnd(12) + ps.map((p) => f(p).toFixed(2).padStart(6)).join(''));
}p 0.0 0.2 0.4 0.6 0.8 1.0
linear 0.00 0.20 0.40 0.60 0.80 1.00
quadOut 0.00 0.36 0.64 0.84 0.96 1.00
cubicInOut 0.00 0.03 0.26 0.74 0.97 1.00
backOut 0.00 0.71 1.03 1.10 1.05 1.00
elasticOut 0.00 1.13 1.03 0.98 1.00 1.00
quadOut covers 64% of the distance in the first 40% of the time and then settles, which reads as "responsive"; backOut goes 10% past the target and comes back, a cheap way to make things feel springy; elasticOut wobbles. Linear motion almost always looks mechanical. The Easing lesson in Math for Games plots these curves.
A tween helper in 30 lines
A game only needs a few features: animate any numeric properties, an easing, a delay, a completion callback, and an update driven by the game loop's dt (so tweens pause with the game). The playground builds one and uses it for three effects: click a coin to collect it (it pops up, spins and shrinks), click the door to slide it open or shut, and press Reset.
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block; cursor: pointer }
button { position: fixed; left: 8px; top: 8px; font: 12px system-ui, sans-serif }</style>
<button id="reset">Reset</button>
<script type="module">
import * as THREE from 'three';
// ---- a minimal tween system ----
const easings = {
linear: (p) => p,
quadOut: (p) => 1 - (1 - p) * (1 - p),
cubicInOut: (p) => (p < 0.5 ? 4 * p ** 3 : 1 - (-2 * p + 2) ** 3 / 2),
backOut: (p) => { const c = 1.70158; return 1 + (c + 1) * (p - 1) ** 3 + c * (p - 1) ** 2; },
};
const tweens = new Set();
function tween(target, to, { duration = 0.5, delay = 0, ease = 'quadOut', onDone } = {}) {
const t = { target, to, from: null, duration, time: -delay, ease: easings[ease], onDone };
tweens.add(t);
return t;
}
function updateTweens(dt) {
for (const t of tweens) {
t.time += dt;
if (t.time < 0) continue; // still waiting for its delay
if (!t.from) t.from = Object.fromEntries(Object.keys(t.to).map((k) => [k, t.target[k]])); // read start values late
const p = Math.min(t.time / t.duration, 1), e = t.ease(p);
for (const k in t.to) t.target[k] = t.from[k] + (t.to[k] - t.from[k]) * e;
if (p === 1) { tweens.delete(t); t.onDone?.(); }
}
}
const killTweensOf = (target) => { for (const t of tweens) if (t.target === target) tweens.delete(t); };
// ---- end of tween system ----
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#1c2232');
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 50);
camera.position.set(0, 2.5, 7);
camera.lookAt(0, 1, 0);
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
scene.add(new THREE.HemisphereLight('#fff', '#334', 1.4));
const sun = new THREE.DirectionalLight('#fff', 2);
sun.position.set(3, 5, 4);
scene.add(sun);
const floor = new THREE.Mesh(new THREE.PlaneGeometry(12, 6), new THREE.MeshStandardMaterial({ color: '#3d4a5f' }));
floor.rotation.x = -Math.PI / 2;
scene.add(floor);
const coinGeo = new THREE.CylinderGeometry(0.3, 0.3, 0.07, 32).rotateX(Math.PI / 2);
const coinMat = new THREE.MeshStandardMaterial({ color: '#ffc928', metalness: 0.4, roughness: 0.3, emissive: '#3a2a00' });
const coins = [-3, -2, -1].map((x) => {
const c = new THREE.Mesh(coinGeo, coinMat);
c.position.set(x, 0.6, 0);
c.userData.home = x;
scene.add(c);
return c;
});
const frame = new THREE.Mesh(new THREE.BoxGeometry(2, 2.6, 0.3), new THREE.MeshStandardMaterial({ color: '#6d5847' }));
frame.position.set(2.2, 1.3, -0.3);
const door = new THREE.Mesh(new THREE.BoxGeometry(1.4, 2.2, 0.2), new THREE.MeshStandardMaterial({ color: '#b07d4f' }));
door.position.set(2.2, 1.1, -0.05);
door.userData.open = false;
scene.add(frame, door);
const raycaster = new THREE.Raycaster(), pointer = new THREE.Vector2();
renderer.domElement.addEventListener('pointerdown', (e) => {
pointer.set((e.offsetX / innerWidth) * 2 - 1, -(e.offsetY / innerHeight) * 2 + 1);
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects([...coins, door], false)[0];
if (!hit) return;
const o = hit.object;
if (o === door) {
killTweensOf(door.position); // interrupt cleanly mid-motion
door.userData.open = !door.userData.open;
tween(door.position, { y: door.userData.open ? 3.3 : 1.1 }, { duration: 0.6, ease: door.userData.open ? 'cubicInOut' : 'backOut' });
} else if (o.visible && !o.userData.taken) {
o.userData.taken = true;
tween(o.position, { y: 1.8 }, { duration: 0.35, ease: 'quadOut' }); // pop up
tween(o.rotation, { y: Math.PI * 4 }, { duration: 0.6, ease: 'quadOut' }); // spin
tween(o.scale, { x: 0, y: 0, z: 0 }, { duration: 0.25, delay: 0.35, ease: 'linear', // then vanish
onDone: () => { o.visible = false; console.log('coin collected'); } });
}
});
document.getElementById('reset').onclick = () => {
coins.forEach((c, i) => {
killTweensOf(c.position); killTweensOf(c.rotation); killTweensOf(c.scale);
Object.assign(c.userData, { taken: false });
c.visible = true;
c.position.set(c.userData.home, 0.6, 0);
c.rotation.set(0, 0, 0);
c.scale.setScalar(0.01);
tween(c.scale, { x: 1, y: 1, z: 1 }, { duration: 0.4, delay: i * 0.1, ease: 'backOut' }); // staggered
});
};
const timer = new THREE.Timer();
let time = 0;
renderer.setAnimationLoop((t) => {
timer.update(t);
const dt = Math.min(Math.max(timer.getDelta(), 0), 0.1);
time += dt;
updateTweens(dt);
for (const c of coins) if (!c.userData.taken) {
c.position.y = 0.6 + Math.sin(time * 3 + c.userData.home) * 0.08; // procedural bob
c.rotation.y += dt * 1.5;
}
renderer.render(scene, camera);
});
</script>Three details make tweens robust in a game:
- Read start values when the tween starts, not when it's created (
fromis filled after the delay), so chained and delayed tweens start from wherever the object is by then. - Kill old tweens on the same property before starting new ones. Otherwise two tweens fight over the door, and the last one to update wins each frame.
- Drive tweens with the game's
dt, so pausing the game (or slow motion) pauses them too.
Libraries
For bigger projects, use a library with timelines, sequencing and more easings:
- tween.js (
@tweenjs/tween.js): small and classic; Three.js even vendors a copy in its addons asthree/addons/libs/tween.module.jsfor its examples. - GSAP: the most complete animation library on the web (timelines, labels, plugins); free to use, but check its current license terms for your project.
- Theatre.js: a visual timeline editor for cutscenes and camera moves.
// tween.js (as vendored in three/addons/libs/tween.module.js)
import { Tween, Easing } from 'three/addons/libs/tween.module.js';
const lift = new Tween(door.position)
.to({ y: 3.3 }, 600) // milliseconds
.easing(Easing.Cubic.InOut)
.onComplete(() => console.log('open'))
.start(time); // time in ms, the same clock you pass to update()
// in the loop:
lift.update(time);Procedural motion
Formulas of time are cheaper and more flexible than tweens for continuous motion:
| Effect | Formula (per frame) |
|---|---|
| Bob | y = base + Math.sin(time * speed + phase) * amplitude |
| Spin | rotation.y += turnRate * dt |
| Pulse | scale = 1 + Math.sin(time * 6) * 0.05 |
| Follow with lag | pos.lerp(target, 1 - Math.exp(-sharpness * dt)) |
| Spring (overshoot and settle) | v += (k * (target − x) − c * v) * dt; x += v * dt |
Give each object a different phase (phase = index or a seeded random) so a row of pickups doesn't bob in perfect unison. A spring is the best tool for interactive things (UI that reacts to the cursor, a camera that kicks back on a shot) because, unlike a tween, it handles a target that changes while it moves:
// A damped spring following a target that jumps from 0 to 1 at t = 0, simulated at 60 Hz.
const k = 120, c = 12; // stiffness and damping
let x = 0, v = 0;
const dt = 1 / 60, target = 1;
const samples = [];
for (let frame = 1; frame <= 60; frame++) {
v += (k * (target - x) - c * v) * dt; // semi-implicit Euler: velocity first...
x += v * dt; // ...then position with the new velocity
if (frame % 6 === 0) samples.push(`${(frame * dt).toFixed(1)}s:${x.toFixed(3)}`);
}
console.log(samples.join(' '));0.1s:0.454 0.2s:0.935 0.3s:1.104 0.4s:1.079 0.5s:1.020 0.6s:0.991 0.7s:0.989 0.8s:0.996 0.9s:1.000 1.0s:1.001
The value overshoots to about 1.10, swings back and settles near 1 within a second. Raise c for less bounce (critical damping is c = 2·√k ≈ 21.9 here), raise k for a faster response.
Test yourself
Which easing makes a value go slightly past its target before settling?
- linear
- quadOut
- backOut
- cubicInOut
The player clicks a door twice quickly and it jitters between two positions. What is the fix?
- Use linear easing
- Stop (kill) the running tween on that property before starting a new one
- Increase the duration
- Use a fixed timestep
Why drive tweens with the game loop's dt instead of the wall clock?
- It's more precise
- So tweens pause and slow down with the game (pause menu, slow motion)
- Wall-clock time isn't available in browsers
- To save memory