Interactive Vision From Zero · Episode 04
Grab & Throw
Grab & Throw is Episode 04 of Interactive Vision From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
This is the one you show people. Pinch your fingers in the air, snatch a ball out of a tumbling pile, wind up, and hurl it across the screen — and watch it ricochet off the walls with the exact speed you flicked your wrist. No controller, no mouse, no gloves. The clip ends and someone always says the same thing: "wait — that's just a webcam?" Yes. That's the whole trick, and you're about to build it.
Under the hood it's four small ideas stacked together: map the pinch point from Episode 03 into 3D space, run a dead-simple physics box full of bouncing spheres, grab the nearest ball when the pinch closes, and — the part that makes it feel real — remember how fast your hand was moving and transfer that velocity to the ball when you let go. Momentum from your fingers. The demo below is already doing it on a synthetic hand; flick through the six stages to watch the machine assemble itself, then point your own camera at it.
What you're looking at
A glass box, viewed head-on, with a few rubbery spheres inside. The bright sphere that tracks the hand is the hand cursor — it lives at the midpoint between your thumb tip and index tip, projected onto a flat plane inside the box. When the synthetic hand's pinch closes (it oscillates open/closed on autoplay so the demo grabs and throws by itself), the cursor turns gold and the nearest ball snaps to it. When the pinch opens, the ball launches with whatever velocity the cursor had in the last few frames. Everything you see is driven by the same 21-landmark hand structure MediaPipe emits, so the moment you flip on your camera, your real hand drops into the exact same code path.
Mirror, stated up front: this is a selfie view, so we flip the X
axis — worldX ∝ (1 − landmark.x). Move your hand right, the cursor goes
right. The synthetic hand is mirrored the same way, so synthetic and camera modes feel
identical. Mirrored axes are the number-one source of "why is it backwards," so we name
it loudly and apply it in exactly one place.
Stage 1 — Hand cursor
Before any physics, just the mapping. The glowing sphere is the pinch midpoint pushed
from normalized image coordinates into world space on a fixed z-plane. This
is the bridge between "vision" and "3D": MediaPipe gives you numbers in [0,1],
and a scene needs meters. Get this right and everything downstream is easy; get it wrong
and your hand will live in the top-left corner forever (the classic normalized-vs-pixel
bug). Notice the cursor pulses gold as the synthetic pinch closes — that's the grab
signal, wired but not yet doing anything.
Stage 2 — Balls + gravity
Now the box has spheres, and they obey a tiny hand-written integrator: every frame
add gravity to velocity, move by velocity × dt, and bounce off the six
walls with restitution (energy kept per bounce). Drag the gravity
and restitution sliders and feel them respond. The hand cursor is here too,
but it can't touch anything yet — it passes straight through. We're proving the physics
is stable on its own before we let the hand interfere.
Stage 3 — Grab (no throw)
Pinch down and the nearest ball within a grab radius attaches to the cursor: its physics pauses and it rides the hand exactly. Open the hand and it simply drops — gravity takes over, no throw yet. This isolates the attach/detach logic. Watch what happens when the synthetic pinch fires while no ball is close: nothing. Grabbing must be conditional on proximity, or you'll yank balls across the room from anywhere, which feels broken.
Stage 4 — Velocity arrow
Here we make the invisible visible. While a ball is held, we track the hand's
velocity as a smoothed position delta over dt, and draw it as an
arrow growing out of the cursor. This is the single most useful debugging view in the
whole episode: the arrow is exactly what the ball will inherit on release. If
the arrow flickers and explodes, your throw will too — which is the cue to smooth and
clamp the velocity (we do). A legible velocity vector is the difference between a throw
that feels intentional and one that feels random.
Stage 5 — Throw
The payoff. On release we set the ball's velocity to that tracked hand velocity,
scaled by throw power, then re-enable its physics — in that order.
The ball leaves your hand carrying your wind-up and ricochets off the walls. This is the
moment the demo stops being a tech toy and becomes a game. Crank throw power
and sling them hard; drop it low for gentle lobs. Everything you flick, it remembers.
Stage 6 — Juice
Same machine, dressed up. Many balls, motion trails, a contact shadow on the floor,
and the restitution + throw power sliders pushed. Set
restitution above 1.0 to make the balls gain energy on each bounce — chaos —
or low for dead, sticky thuds. This is where you'd record the clip. It's the same four
ideas from the stages above, just turned up until it sings.
How the code works
Four pieces do all the work. We'll look at each in isolation; in the demo they're
wired into one onLandmarks(hand) function that both the synthetic loop and
the real camera feed call — so there's a single source of truth.
(a) Normalized landmark → world-space plane (with the mirror)
The pinch midpoint arrives as two numbers in [0,1]. We flip X for the
selfie mirror, recenter to [-0.5, 0.5], scale by the box's half-extents,
and pin a fixed z. Fixing z is the key decision: landmark
depth is a noisy hint, not metric, so instead of trusting it we choose a single plane
the hand lives on. That keeps grabbing predictable and the math trivial:
// Box spans [-HX,HX] x [-HY,HY] x [-HZ,HZ] in world units.
// hand = 21 landmarks, each {x,y,z} normalized to [0,1] in image space.
function pinchToWorld(hand) {
const thumb = hand[4], index = hand[8];
const mx = (thumb.x + index.x) * 0.5; // pinch midpoint, normalized
const my = (thumb.y + index.y) * 0.5;
const sx = 1 - mx; // MIRROR: selfie view, flip X once
const wx = (sx - 0.5) * 2 * HX; // [0,1] → [-HX, HX]
const wy = (0.5 - my) * 2 * HY; // y is down in images → flip to world up
return new THREE.Vector3(wx, wy, Z_PLANE); // fixed z: ignore noisy landmark depth
}
(b) The sphere integrator + wall collision (dt-correct)
The whole physics engine. Gravity is an acceleration, so it scales with dt;
position moves by velocity × dt. On hitting a wall we push the ball back
inside and flip that axis' velocity, multiplied by restitution. Using dt
everywhere — never a per-frame constant — is what keeps the simulation identical at
30fps and 144fps:
function stepBall(b, dt, gravity, restitution) {
if (b.held) return; // held balls are driven by the hand, not physics
b.vel.y -= gravity * dt; // gravity: an acceleration → × dt
b.pos.addScaledVector(b.vel, dt); // integrate position: pos += vel * dt
const lim = [HX - b.r, HY - b.r, HZ - b.r]; // wall positions per axis
['x', 'y', 'z'].forEach((ax, i) => {
if (b.pos[ax] > lim[i]) { b.pos[ax] = lim[i]; b.vel[ax] *= -restitution; }
if (b.pos[ax] < -lim[i]) { b.pos[ax] = -lim[i]; b.vel[ax] *= -restitution; }
});
}
(c) Grab: nearest-within-radius, only on pinch-down
We detect the rising edge of the pinch (justPressed = closed now, open
last frame) using the hysteresis detector from Episode 03. On that edge — and only then
— we scan for the closest ball and attach it only if it's inside the grab
radius. The radius guard is what stops "grabbing nothing" from teleporting a distant
ball into your hand:
// justPressed: pinch closed this frame but was open last frame (edge, not level).
if (justPressed && !held) {
let best = null, bestD = GRAB_RADIUS; // seed with the radius: misses stay null
for (const b of balls) {
const d = b.pos.distanceTo(cursor);
if (d < bestD) { bestD = d; best = b; }
}
if (best) { best.held = true; held = best; } // attach only if something was in range
}
(d) Velocity tracking + release transfer
While a ball is held we lerp a smoothed velocity toward the raw per-frame
(delta / dt), then clamp its magnitude. Both matter: raw landmark
velocity is spiky, and one noisy frame at release can launch a ball at light speed. On
justReleased we copy the smoothed velocity (× throw power) into the ball,
then clear held so physics resumes next frame with the right
velocity already set:
// every frame the cursor moves:
const raw = tmp.subVectors(cursor, prevCursor).divideScalar(dt);
handVel.lerp(raw, 0.35); // smooth: low-pass the spikes
if (handVel.length() > MAX_HAND_VEL) // clamp: no light-speed throws
handVel.setLength(MAX_HAND_VEL);
if (justReleased && held) {
held.vel.copy(handVel).multiplyScalar(throwPower); // 1) set velocity FIRST
held.held = false; // 2) THEN unpause → physics resumes correctly
held = null;
}
Common pitfalls
- Throws explode. Raw hand velocity is noisy, and a single bad frame at the instant of release becomes a rocket. Always smooth the velocity (a lerp / small moving window) and clamp its magnitude. The Stage 4 arrow is your canary — if it jitters wildly, so will your throws.
- Physics changes with frame rate. If you write
vel.y -= 0.3per frame, your game is slow-motion on a 144Hz monitor and hyperspeed on a 30Hz one. Multiply every accumulation bydt(and capdtso a background tab doesn't teleport everything on the first frame back). - Grabbing nothing. If you attach the nearest ball
unconditionally on pinch, you'll yank a ball from across the box. Seed your
search distance with the grab radius so a miss leaves
heldnull. - 2D → 3D ambiguity. A landmark is two reliable numbers plus a shaky depth hint. Don't try to reconstruct true depth — pick a z-plane and map onto it. State the plane; it makes grabbing deterministic.
- Mirror. Forget the
1 − xflip and the hand moves the wrong way. Apply it exactly once, in the landmark→world mapping, to both synthetic and camera input. - Re-enabling physics on the wrong frame. On release, set the
ball's velocity before you clear its
heldflag. Flip the order and the integrator runs once with zero velocity, eating your throw.
Exercises
- Two-hand grab. Set
numHands: 2and run two cursors, each with its own pinch state and held ball. Two people — or two hands — juggling in one box. (You'll want a per-handhandVelandheld.) - Add a hoop and count baskets. Drop a ring (a torus) into the scene and detect when a ball passes through its plane within its radius while moving the right direction. Increment a score. Suddenly it's a sport.
- Sticky vs bouncy. Swap restitution per-ball: some at
0.2(dead thuds), some at0.98(superballs). Color them by their bounciness so you can read the physics at a glance.
What's next
Episode 05 — Gesture Recognition. The pinch is one gesture; next we read the whole hand. From per-finger joint angles we'll classify open palm, fist, point, peace, and thumbs-up with a tiny, readable classifier — no ML training — and map each to an action. Once you can name what the hand is doing, every interaction in this series gets a richer vocabulary.