# Mouse look

> A first-person camera: click to capture the mouse with usePointer().lock(), turn with movementX and movementY.

Example `mouse-look`, running at https://nacatamalon.com/en/examples/mouse-look. The whole catalogue: https://nacatamalon.com/llms/examples.md.

Click the game and `usePointer().lock()` captures the mouse: the cursor hides, and `onMove` keeps reporting `movementX` and `movementY` however far the mouse goes, which turn the camera. **WASD** walks.

**Esc** gives the mouse back. `isLocked()` turns `false` on its own, and the HUD reads it every frame to show the hint again.

The browser only captures the mouse in answer to a click or a key press, so `lock()` is called from `onDown`. Anywhere else it answers `false` instead of throwing. `raw: true` asks for the mouse's own movement, without the system's acceleration, where the browser offers it.

## Code

`index.ts`:

```ts
import { Hud } from './scenes/hud';
import { createGame } from 'nacatamalon';
import * as Settings from './settings';
import { Room } from './scenes/demo';

const game = createGame('#app', {
    width: Settings.WIDTH,
    height: Settings.HEIGHT,
    background: '#0a0a18'
});

// Declare Scenes
game({
    Room,
    Hud
});
```

`components/pillars.ts`:

```ts
import { createMesh, getColor, useCubeGeometry, usePlaneGeometry } from 'nacatamalon';

import * as Settings from '../settings';

export const Pillars = () => {
    createMesh({
        geometry: usePlaneGeometry({
            width: 24,
            depth: 24
        }),
        tint: '#2a2d3e'
    });

    // A ring of pillars to look around at.
    const pillar = useCubeGeometry({
        width: 1,
        height: 3,
        depth: 1
    });

    for (let i = 0;i < 12;i++) {
        const angle = (i / 12) * Math.PI * 2;

        createMesh({
            geometry: pillar,
            tint: getColor(Settings.COLORS[i % Settings.COLORS.length]),
            transform: {
                x: Math.sin(angle) * 8,
                y: 1.5,
                z: Math.cos(angle) * 8
            },
        });
    }
};
```

`hooks/use_first_person.ts`:

```ts
import { useKeyboard, usePointer, useUpdate } from 'nacatamalon';
import { clamp } from 'nacatamalon/math';
import * as Settings from '../settings';
import type { TCamera3d } from 'nacatamalon';

export const useFirstPerson = (camera: TCamera3d) => {
    const pointer = usePointer();
    const keys = useKeyboard();

    // Capturing has to come from a click: the browser allows it only then. raw asks for the
    // mouse's own movement, without the system's acceleration, where the browser has it.
    pointer.onDown(() => {
        if (!pointer.isLocked()) {
            void pointer.lock({
                raw: true
            });
        }
    });

    // movementX/Y keep coming however far the mouse goes; the cursor and screenX/Y stay put.
    pointer.onMove(({ movementX, movementY }) => {
        if (!pointer.isLocked()) {
            return;
        }

        camera.transform.rotationY -= movementX * Settings.SENSITIVITY;
        camera.transform.rotationX = clamp(camera.transform.rotationX - movementY * Settings.SENSITIVITY, -1.4, 1.4);
    });

    useUpdate((delta) => {
        const forward = Number(keys.isDown('w')) - Number(keys.isDown('s'));
        const strafe = Number(keys.isDown('d')) - Number(keys.isDown('a'));
        const yaw = camera.transform.rotationY;

        camera.transform.x += (-Math.sin(yaw) * forward + Math.cos(yaw) * strafe) * Settings.SPEED * delta;
        camera.transform.z += (-Math.cos(yaw) * forward - Math.sin(yaw) * strafe) * Settings.SPEED * delta;
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useAmbientLight, useCamera3d, useDirectionalLight, useScene, useSpawn, useReady } from 'nacatamalon';

import { Pillars } from '../components/pillars';
import { useFirstPerson } from '../hooks/use_first_person';

export const Room = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 70,
        transform: {
            y: 1.6,
            z: 6
        }
    });

    useDirectionalLight({
        intensity: 1.1
    });
    useSpawn(() => {
        useAmbientLight({
            intensity: 0.35
        });
    })();

    useSpawn(Pillars)();
    useFirstPerson(camera);

    const scene = useScene();

    useReady(() => scene.launch('Hud'));

    return createScene();
};
```

`scenes/hud.ts`:

```ts
import { createScene, createText, usePointer, useUpdate } from 'nacatamalon';

// Drawn over the room. It reads isLocked() every frame: Esc gives the mouse back without the game
// asking, and this notices on its own.
export const Hud = () => {
    const pointer = usePointer();

    const hint = createText({
        text: 'CLICK TO LOOK  -  WASD TO WALK  -  ESC TO LET GO',
        style: {
            fontSize: 8
        },
        tint: '#ffffff',
        anchor: {
            x: 0.5,
            y: 0.5
        },
        transform: {
            x: 240,
            y: 160
        },
    });

    const crosshair = createText({
        text: '+',
        style: {
            fontSize: 16
        },
        tint: '#ffffff',
        anchor: {
            x: 0.5,
            y: 0.5
        },
        transform: {
            x: 240,
            y: 160
        }
    });

    useUpdate(() => {
        hint.visible = !pointer.isLocked();
        crosshair.visible = pointer.isLocked();
    });

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
export const SENSITIVITY = 0.0025;
export const SPEED = 4;
export const COLORS = ['#ff6b6b', '#f5c518', '#4cff91', '#60a5fa', '#c084fc', '#ff9f43'];
```
