Skip to content

Face gestures ​

In a face-tracking project, scripts can be played with the face: open the mouth to eat, smile to charge, wink to fire, nod to say yes. this.face reads the person in front of the camera as named gestures, as state you can check every frame and as events you can listen for, so a game doesn't have to poll.

this.face is null in any other kind of project, and in the editor viewport. Everything below works in the Preview and on a device.

Reading state ​

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";

export class SmileToGrow extends Behaviour {
  onUpdate() {
    const face = this.face;
    if (!face?.isTracking()) return;
    const scale = face.isSmiling() ? 1.5 : 1;
    this.transform.scale.x = scale;
    this.transform.scale.y = scale;
    this.transform.scale.z = scale;
  }
}
MethodTrue while
isMouthOpen()The mouth is open
isMouthClosed()A face is in view with its mouth closed. With no face, neither is true
isSmiling()Smiling, lips closed or open
isBlinking()Both eyes are shut right now
isEyeClosed(side)That eye is shut, winking or blinking
isWinking(side?)A wink is being held. With no side, either eye
areBrowsRaised()The brows are up
getHeadTilt()"left" or "right": the side of the picture the top of the head leans to. null when upright
getHeadAngles(){ yaw, pitch, roll } in degrees, or null

Gestures are read before scripts update, so anything read in onUpdate is this frame's.

Hearing gestures ​

A blink is over in two or three frames and a nod takes under a second, so a script checking state can miss them. Listen instead, with the onFaceGesture hook, which every script gets:

ts
import { Behaviour, type FaceGestureEvent } from "@relu-interactives/spatial-ecs";

export class Fire extends Behaviour {
  data = { shots: 0 };

  onFaceGesture(gesture: FaceGestureEvent) {
    if (gesture.name === "winkLeft" || gesture.name === "winkRight") {
      this.data.shots += 1;
    }
  }
}

Or with this.face.on(name, listener), which returns what takes the listener off. "*" hears every gesture.

ts
import { Behaviour, type Unsubscribe } from "@relu-interactives/spatial-ecs";

export class CountBlinks extends Behaviour {
  data = { blinks: 0 };
  private stop: Unsubscribe | null = null;

  init() {
    this.stop = this.face?.on("blink", () => {
      this.data.blinks += 1;
    }) ?? null;
  }

  dispose() {
    this.stop?.();
  }
}

this.face.didGesture(name) is true for the one frame a gesture fired on, for a script that would rather poll.

GestureWhen
mouthOpen, mouthCloseThe mouth opens, or closes again
smile, smileEndA smile starts, or ends
blinkBoth eyes shut. Fires as they close, once per closure
eyesClose, eyesOpenBoth eyes shut, then open again, however long
winkLeft, winkRightOne eye shut and held for a moment. The picture's left and right
browsRaise, browsLowerThe brows go up, or come back down
nodThe head goes down and back, or up and back
headShakeThe head turns from side to side
tiltLeft, tiltRight, tiltEndThe top of the head leans to that side of the picture, or comes back

The event carries name and values, how far each expression was from the resting face at that moment. When the face leaves the picture, everything that was on ends: a mouthOpen always gets its mouthClose.

Hooks don't run while the world is paused. Listeners added with on() do, so a pause menu can be closed with a gesture.

Left and right ​

Left and right are the picture's, as they are everywhere on the head: winkLeft is the eye on the left of the picture. On a selfie the picture is a mirror, so that's the player's own left eye. On a camera pointed at someone else, it's their right.

Where things are on the face ​

getWorldPosition(point) is where a place on the face is in the world on this frame, and getScreenPosition(point) where it is on screen, in CSS pixels from the top left of the page, like a pointer event's clientX and clientY. The places are the head's attach points (see Face tracking); mouth, upperLip, chin and the jaw follow the expression, so mouth is between the lips as they open. Both return null with no face.

isTouching(point, position, radius) says whether a world position lands on a place as the viewer sees it. Depth doesn't count, so something falling down the screen reaches the mouth when it looks like it does, whatever its distance. radius is in face widths on screen, 0.2 by default.

A falling donut, eaten by opening the mouth when it gets there:

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";
import * as THREE from "three";

export class DonutGame extends Behaviour {
  data = { score: 0, missed: 0, fallSpeed: 16 };
  private donut: THREE.Mesh | null = null;

  onUpdate() {
    const face = this.face;
    const mouth = face?.getWorldPosition("mouth");
    if (!face || !mouth) return;

    if (!this.donut) {
      this.donut = new THREE.Mesh(
        new THREE.TorusGeometry(2.1, 1, 12, 28),
        new THREE.MeshStandardMaterial({ color: "#ff6fa8" }),
      );
      // the world is in centimetres here: start 22 cm above the mouth
      this.donut.position.set(mouth.x, mouth.y + 22, mouth.z + 4);
      this.world.getScene().add(this.donut);
    }

    this.donut.position.y -= this.data.fallSpeed * this.deltaTime;
    if (face.isMouthOpen() && face.isTouching("mouth", this.donut.position, 0.28)) {
      this.data.score += 1;
      this.world.getScene().remove(this.donut);
      this.donut = null;
    } else if (this.donut.position.y < mouth.y - 18) {
      this.data.missed += 1;
      this.world.getScene().remove(this.donut);
      this.donut = null;
    }
  }
}

In a face-tracking project the world is the camera's space in centimetres: the camera is at the origin looking down -Z, and a face at arm's length is about 45 cm away. getScreenFaceWidth() is the face's width on screen in CSS pixels, the right yardstick for a distance on screen since it's the same near or far.

How a gesture is decided ​

Each gesture reads one measure of the face from the tracker, 0 to 1:

MeasureFrom
mouthOpenThe jaw opening
smileBoth corners of the mouth, averaged, so a lopsided smile counts
eyeLeft, eyeRightEach eyelid closing
browsRaisedInner and outer brows, averaged

A resting face isn't zero. Some people's mouths rest a little open, glasses and a phone held low read as half-closed eyes, and some faces rest with raised brows. So every measure is taken from this person's resting face: over the first 600 ms of tracking it takes the 40th percentile of each, and from then on follows it, quickly downwards and slowly upwards, and never upwards while that gesture is on. Each rest is capped, so someone who smiles all through the first second still reads as smiling. getGestureValues() returns the measures as the gestures see them, 0 at rest. resetNeutral() measures again from the next frame: call it when you've just asked the player to relax.

Every gesture has two thresholds, one to come on and a lower one to go off, so a value hovering at the edge doesn't flicker, and most have to hold for a moment before they count, so one wild frame isn't a gesture.

Blink or wink. A blink is both eyes going together, and its threshold is lower than one eye's, because a real blink is over before the tracker sees it all the way down. A wink is one eye shut, clearly more than the other, held for winkHoldMs. A blink with one eye a little ahead of the other doesn't turn into a wink.

Nod, shake and tilt come from the head's angles. A nod is the head going down (or up) by nodDegrees and coming back near where it started within about a second. A shake is the head reversing direction twice, each swing at least shakeDegrees. Looking away and staying there is neither. A tilt is measured from how this person holds their head.

Thresholds ​

ThresholdDefaultWhat it is
mouthOpenon 0.28, off 0.16A clear open mouth. Talking mostly stays under it
smileon 0.4, off 0.28Takes a closed-lip smile
eyeClosedon 0.22, off 0.12One eye
blinkon 0.2, off 0.12Both eyes, averaged
browsRaisedon 0.2, off 0.12
winkMargin0.12How much more closed the winking eye is than the other
winkHoldMs160How long one eye stays shut before it's a wink
headTilton 14°, off 9°From how the person holds their head
nodDegrees8How far a nod goes and comes back
shakeDegrees12How far each swing of a shake goes

Change any of them, and the rest stay:

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";

export class EasyMode extends Behaviour {
  init() {
    // a smaller mouth counts, for younger players
    this.face?.setGestureThresholds({ mouthOpen: { on: 0.2, off: 0.1 } });
  }
}

getGestureThresholds() returns the ones in use.

Raw expressions ​

The tracker's own blendshapes are still there: getBlendshape("jawOpen"), getBlendshapes(). They're ARKit-style names, 0 to 1, and not measured from the resting face. Their Left and Right are the face's own as the picture shows it, so eyeBlinkLeft is the eye on the right of the picture: use the gestures for left and right.

What it can't tell ​

It reads one face, the one the tracker found. Talking can open the mouth past the threshold, and looking down narrows the eyes, which a slow change of rest absorbs but a sudden glance down can read as a blink. A very fast blink between two slow frames can be missed entirely. When it matters, ask for something deliberate: a wide mouth, a wink held, a nod.