# World controls — walk, look and fly through a 3D world on a phone and a desktop

> 3D garden I can // walk around inExploreAny 3D place the person walks through as a player, on foot or flying, first-person, on a phone and a desktop: a 3D garden, house, museum, cave, island, maze, city or ship to walk around in. Load it beside three-js for every walked-through world; a model turned or spun on its own (a product viewer) is three-js alone. The useWorldControls hook from use-vibes: left thumb walks on a floating stick, right thumb looks, flick up to jump, tap and hold act on what is under the finger, a 🎥 button cycles free cam, first person and shoulder views, and the desktop gets pointer lock, WASD and Space. walk-through, first-person, walk around, explore, wander, fly around, 3D world

Source: https://good.vibes.diy/docs/reference/world-controls

## Walk + look: move through a 3D world

A 3D world you walk, fly or look around in gets its controls from `useWorldControls` (from `use-vibes`), on phone and desktop alike. Hand it the root element and what each act means; the hook owns the gestures, keeps the root `touch-none`, and sizes the lens when you pass it the camera.

**Bind the root.** The ref you hand the hook goes on the outermost element the world fills, the one around the canvas and the HUD (`<div ref={rootRef} className="relative h-dvh w-full overflow-hidden touch-none">`). A ref the hook gets but no element carries attaches nothing, and the world cannot be walked.

Left half walks: a floating stick appears under the thumb. Right half looks: drag to turn, and a finger held near the screen's edge keeps turning.

Tap acts on what is under the finger; press and hold is the second action; a quick upward flick on the look side jumps.

- **The jump is judged as the finger lifts**, and the flick's up/down look is held back, so the
  camera stays level through every jump.
- **`mode: "player"`** walks, looks and flicks; **`mode: "free"`** orbits a camera that zooms
  with a pinch or the mouse wheel (`onPinch(factor)`, under 1 zooms in). With `flying: true`, a
  flick down (`onFlick("down")`) sinks.
- **The callbacks speak screen sense.** `onMove(x, y)` is the walk vector with forward at `y < 0`;
  `onLook(dx, dy)` and `onTurn(yaw, pitch)` arrive in radians, applied the same way; `onTap`,
  `onHold` and `onAim` carry client coordinates.
- **Call `tick(dt)` once per frame** from the animation loop; the edge turn, the hold timer and
  the finger trail advance on that clock, and `keys` holds every key code down right now.
- **The lens follows the screen.** Pass the `THREE.PerspectiveCamera` as `camera` and the hook
  keeps its aspect current and widens the view on a phone held upright.
- **HUD controls live inside the root.** A press on a button, input or link there is that
  control's own and never a world tap; mark any other piece that keeps its own touches (a slider,
  a chip row) with `data-world-controls-ignore`.

A 🎥 button outside the menu cycles the views; on a phone the world opens in a free-cam overview that frames the whole scene. The views are **Free cam → First person → Shoulder view**; a desktop visitor opens in first person.
The overview's distance is the app's: scale the orbit radius by
`0.36 / (tan(fov / 2) · aspect)`, clamped to 1–2.2×, each frame, so a phone held upright still
frames the whole scene.

The one-line hint follows the current view.

The ☰ menu holds everything else, in this order: the views by name, fullscreen, how to play,
who else is here and what they did lately (players and activity), then invite a friend and all
worlds. Every world's menu carries the first three: the views, a Fullscreen entry that fills the
phone with the world (`requestFullscreen()` on the root, from the tap itself), and a How to play
entry that keeps the gestures one tap away after the hint has moved on.

**The desktop twin is the same world.** In the player views a click-to-play overlay calls
`requestLock()`, so the mouse looks under pointer lock; WASD or the arrows walk and Space jumps.
The V key cycles the views just as the 🎥 button does, once per press, and the overlay's control legend names it (`V views`).
`locked` reports the lock, so the overlay comes back when the player presses Esc, and `isTouch`
keeps the overlay off phones. While locked, a click under the crosshair is the tap and a
right-click is the hold (`onTap` / `onHold` at the screen centre). Free cam needs no lock: drag
orbits, a click is `onTap`, a right-click is `onHold`, and the wheel zooms.

### `App.jsx`
```jsx
import React from "react";
import * as THREE from "three";
import { useWorldControls } from "use-vibes";
import { Button, Card, Heading, IconButton, Stack, Text } from "@vibes.diy/ui";
import { readLook, watchLook } from "./lib/look.js";

const VIEWS = ["Free cam", "First person", "Shoulder view"];
const HINT = {
  "Free cam": "drag to look around · pinch to zoom · 🎥 to step in",
  "First person": "left thumb walks · right thumb looks · flick up to jump",
  "Shoulder view": "tap a hedge to bloom it · hold to trim it back",
};
const stop = (e) => e.stopPropagation();

export default function App() {
  const rootRef = React.useRef(null);
  const canvasRef = React.useRef(null);
  const [camera] = React.useState(() => new THREE.PerspectiveCamera(70, 1, 0.1, 500));
  const [view, setView] = React.useState(() => (matchMedia("(pointer: coarse)").matches ? "Free cam" : "First person"));
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [howTo, setHowTo] = React.useState(false);
  const [full, setFull] = React.useState(false);
  const me = React.useRef({ pos: new THREE.Vector3(0, 0, 12), yaw: 0, pitch: 0, move: [0, 0], vy: 0, zoom: 34 });
  const world = React.useRef({ hedges: [], colors: null });

  const turn = (yaw, pitch) => {
    me.current.yaw += yaw;
    me.current.pitch = Math.max(-1.5, Math.min(1.5, me.current.pitch + pitch));
  };
  const look = (dx, dy) => turn(-dx, -dy); // radians, screen sense: a drag right turns right
  const hedgeAt = (x, y) => {
    const r = rootRef.current.getBoundingClientRect(); // taps arrive in client coordinates
    const ray = new THREE.Raycaster();
    ray.setFromCamera(new THREE.Vector2(((x - r.left) / r.width) * 2 - 1, 1 - ((y - r.top) / r.height) * 2), camera);
    return ray.intersectObjects(world.current.hedges)[0]?.object;
  };
  const bloom = (hedge, on) => {
    if (!hedge) return;
    hedge.userData.bloom = on;
    hedge.material.color.set(on ? world.current.colors.accent : world.current.colors.lead);
  };
  const { isTouch, locked, requestLock, tick } = useWorldControls(rootRef, {
    mode: view === "Free cam" ? "free" : "player",
    camera,
    onMove: (x, y) => (me.current.move = [x, y]),
    onLook: look,
    onTurn: look,
    onPinch: (factor) => (me.current.zoom = Math.max(8, Math.min(60, me.current.zoom * factor))),
    onTap: (x, y) => bloom(hedgeAt(x, y), true),
    onHold: (x, y) => bloom(hedgeAt(x, y), false),
    onFlick: (dir) => dir === "up" && me.current.pos.y === 0 && (me.current.vy = 7),
  });
  const live = React.useRef({});
  live.current = { tick, view };

  React.useEffect(() => {
    const root = rootRef.current;
    const renderer = new THREE.WebGLRenderer({ canvas: canvasRef.current, antialias: true });
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
    const size = new ResizeObserver(() => renderer.setSize(root.clientWidth, root.clientHeight, false));
    size.observe(root);
    const scene = new THREE.Scene();
    scene.fog = new THREE.Fog(0x000000, 30, 90);
    const light = new THREE.HemisphereLight(0xffffff, 0xffffff, 1.4);
    scene.add(light);
    const groundGeo = new THREE.PlaneGeometry(60, 60);
    const ground = new THREE.Mesh(groundGeo, new THREE.MeshLambertMaterial());
    ground.rotation.x = -Math.PI / 2;
    scene.add(ground);
    const hedgeGeo = new THREE.BoxGeometry(5, 2, 1);
    for (let i = 0; i < 10; i++) {
      const hedge = new THREE.Mesh(hedgeGeo, new THREE.MeshLambertMaterial());
      hedge.position.set(Math.cos(i * 0.63) * 18, 1, Math.sin(i * 0.63) * 18);
      hedge.lookAt(0, 1, 0);
      scene.add(hedge);
      world.current.hedges.push(hedge);
    }
    // The garden wears the app's look: sky, light, ground and hedges all come from its tokens, and
    // a restyle repaints them in place while the player keeps walking.
    const paint = (colors) => {
      world.current.colors = colors;
      const sky = new THREE.Color(colors.backdrop).lerp(new THREE.Color(colors.lead), 0.2);
      scene.background = sky;
      scene.fog.color.copy(sky);
      light.color.set(colors.surface);
      light.groundColor.set(colors.lead);
      ground.material.color.set(colors.surface);
      for (const hedge of world.current.hedges) hedge.material.color.set(hedge.userData.bloom ? colors.accent : colors.lead);
    };
    paint(readLook(root));
    const unwatch = watchLook(root, paint);

    let raf = 0;
    let last = performance.now();
    const frame = (now) => {
      const dt = Math.min((now - last) / 1000, 1 / 30);
      last = now;
      live.current.tick(dt);
      const m = me.current;
      const fwd = new THREE.Vector3(-Math.sin(m.yaw), 0, -Math.cos(m.yaw));
      const side = new THREE.Vector3(-fwd.z, 0, fwd.x);
      m.pos.addScaledVector(fwd, -m.move[1] * 5 * dt).addScaledVector(side, m.move[0] * 5 * dt); // forward is y < 0
      m.vy -= 20 * dt;
      m.pos.y = Math.max(0, m.pos.y + m.vy * dt);
      if (m.pos.y === 0) m.vy = 0;
      if (live.current.view === "Free cam") {
        // Back the overview off on a narrow screen so the whole garden stays in frame.
        const fit = Math.min(2.2, Math.max(1, 0.36 / (Math.tan((camera.fov * Math.PI) / 360) * camera.aspect)));
        const d = m.zoom * fit;
        camera.position.set(m.pos.x + Math.sin(m.yaw) * d, d * 0.7, m.pos.z + Math.cos(m.yaw) * d);
        camera.lookAt(m.pos);
      } else {
        camera.position.copy(m.pos).y += 1.6;
        if (live.current.view === "Shoulder view") camera.position.addScaledVector(fwd, -4).y += 1;
        camera.rotation.set(m.pitch, m.yaw, 0, "YXZ");
      }
      renderer.render(scene, camera);
      raf = requestAnimationFrame(frame);
    };
    raf = requestAnimationFrame(frame);

    return () => {
      cancelAnimationFrame(raf);
      unwatch();
      size.disconnect();
      world.current.hedges.forEach((hedge) => hedge.material.dispose());
      world.current.hedges = [];
      hedgeGeo.dispose();
      groundGeo.dispose();
      ground.material.dispose();
      renderer.dispose();
    };
  }, [camera]);

  const cycle = () => setView((v) => VIEWS[(VIEWS.indexOf(v) + 1) % VIEWS.length]);
  React.useEffect(() => {
    // V cycles the views on a keyboard, once per press; a text field keeps its own V.
    const onKey = (e) => {
      if (e.code !== "KeyV" || e.repeat || e.target.closest?.("input, textarea, [contenteditable]")) return;
      cycle();
    };
    const onFull = () => setFull(document.fullscreenElement !== null);
    addEventListener("keydown", onKey);
    document.addEventListener("fullscreenchange", onFull);
    return () => {
      removeEventListener("keydown", onKey);
      document.removeEventListener("fullscreenchange", onFull);
    };
  }, []);
  const toggleFullscreen = () => {
    if (document.fullscreenElement) document.exitFullscreen();
    else if (document.fullscreenEnabled) rootRef.current.requestFullscreen().catch(() => {});
  };
  return (
    <div ref={rootRef} className="relative h-dvh w-full overflow-hidden bg-background text-foreground select-none touch-none">
      <canvas ref={canvasRef} className="absolute inset-0 block w-full h-full select-none touch-none" />
      <div className="absolute top-3 left-3 pointer-events-none">
        <Text size="sm">{HINT[view]}</Text>
      </div>
      <div className="absolute top-3 right-3 flex gap-2" onPointerDown={stop}>
        <IconButton icon="🎥" label={`View: ${view}`} onClick={cycle} />
        <IconButton icon="☰" label={menuOpen ? "Hide menu" : "Show menu"} onClick={() => setMenuOpen(!menuOpen)} />
      </div>
      {menuOpen && (
        <div className="absolute top-16 right-3 w-72" onPointerDown={stop}>
          <Card>
            <Stack gap={2}>
              <Heading level={2}>Hedge Garden</Heading>
              {VIEWS.map((v) => (
                <Button key={v} variant={v === view ? "solid" : "quiet"} onClick={() => setView(v)}>
                  {v}
                </Button>
              ))}
              <Button variant="quiet" onClick={toggleFullscreen}>
                {full ? "Exit fullscreen" : "Fullscreen"}
              </Button>
              <Button variant="quiet" onClick={() => setHowTo(!howTo)}>
                How to play
              </Button>
              {howTo && (
                <Text size="sm" muted>
                  Left thumb walks, right thumb looks. Tap a hedge to bloom it, hold to trim it, flick up to jump. On a
                  keyboard, V changes the view.
                </Text>
              )}
            </Stack>
          </Card>
        </div>
      )}
      {!isTouch && !locked && view !== "Free cam" && (
        <div className="absolute inset-0 z-20 flex items-center justify-center bg-background/80" onPointerDown={stop}>
          <Card>
            <Stack gap={3}>
              <Heading level={2}>Hedge Garden</Heading>
              <Button size="lg" onClick={requestLock}>
                Click to play
              </Button>
              <Text size="sm" muted>
                WASD walk · mouse look · Space jump · click bloom · V views · Esc frees the mouse
              </Text>
            </Stack>
          </Card>
        </div>
      )}
    </div>
  );
}
```

Grow it by changing what the acts mean: `voxel` makes the tap build and the hold break, a ruin
makes the tap open a door. The gesture numbers live in the hook; pass `tune` to adjust them.
