# Triggers and contacts

> Crates cross a sensor band and recolour themselves with onEnter and onExit, knowing which object they met.

Example `physics-2d-triggers`, running at https://nacatamalon.com/en/examples/physics-2d-triggers. The whole catalogue: https://nacatamalon.com/llms/examples.md.

Crates fall through a sensor band and report it themselves: red before, yellow inside, green after. Every body has `onEnter` and `onExit`, which call back with **the other object**, so you can ask whether it was the checkpoint or just another crate.

`sensor: true` makes a collider detect without resolving: things pass straight through. And listening with `onEnter` is what turns contact reporting on: a body nobody listens to costs nothing.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';

import { installPhysics2d } from 'nacatamalon/physics2d';
import * as Settings from './settings';
import { Scene } from './scenes/demo';

installPhysics2d();

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

// Declare Scenes
game({
    Scene
}, 'Scene');
```

`components/checkpoint.ts`:

```ts
import { createSprite, getColor, usePhysicsBody2d } from 'nacatamalon';

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

// The checkpoint. Drawn as a see-through band so you can watch bodies INSIDE it, which is
// the whole proof that a sensor does not resolve the contact. Its NAME is what the crates
// recognise, and a spawned object is named after the function that built it.
export const Checkpoint = () => {
    createSprite({
        tint: {
            ...getColor('#5db6ff'),
            a: 0.22
        },
        width: Settings.WIDTH - Settings.WALL * 2,
        height: Settings.ZONE_H,
        zIndex: -1,
        transform: {
            x: Settings.WIDTH / 2,
            y: Settings.ZONE_Y + Settings.ZONE_H / 2
        },
    });
    usePhysicsBody2d({
        body: 'static',
        collider: {
            shape: 'rect',
            width: Settings.WIDTH - Settings.WALL * 2,
            height: Settings.ZONE_H
        },
        sensor: true,
    });
};
```

`components/crate.ts`:

```ts
import { createSprite, usePhysicsBody2d, useSelf } from 'nacatamalon';

import { getPhysicsBody2d } from 'nacatamalon/physics2d';
import * as Settings from '../settings';

// Crates. Each one watches for the checkpoint and reports its own state by colour.
export const Crate = (x: number, y: number, size: number) => {
    const self = useSelf();

    const art = createSprite({
        tint: Settings.FALLING,
        width: size,
        height: size,
        transform: {
            x: x,
            y: y
        }
    });

    usePhysicsBody2d({
        body: 'dynamic',
        collider: {
            shape: 'rect',
            width: size,
            height: size
        },
        friction: 0.4,
        bounce: 0.1,
        density: 1,
    });

    // Its body, asked for right after the collider is declared. Nothing in the editor while the
    // scene is being built, where nothing simulates.
    const body = getPhysicsBody2d(self);

    if (body) {
        // A crate hears about EVERY contact it has: other crates, the floor, the zone. The
        // name check is what turns that stream into "did I reach the checkpoint". In a real
        // game this would be a tag or a piece of state rather than a name, but the shape of
        // the filter is the same.
        body.onEnter((other) => {
            if (other.name === 'Checkpoint') {
                art.tint = Settings.INSIDE;
            }
        });
        body.onExit((other) => {
            if (other.name === 'Checkpoint') {
                art.tint = Settings.PASSED;
            }
        });
    }
};
```

`components/solid.ts`:

```ts
import { createSprite, usePhysicsBody2d } from 'nacatamalon';

// came out the other side

export const Solid = (x: number, y: number, w: number, h: number) => {
    createSprite({
        tint: '#2a2a3a',
        width: w,
        height: h,
        transform: {
            x: x,
            y: y
        }
    });
    usePhysicsBody2d({
        body: 'static',
        collider: {
            shape: 'rect',
            width: w,
            height: h
        },
        friction: 0.7
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, usePhysicsWorld2d, useSpawn } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';

import * as Settings from '../settings';
import { Solid } from '../components/solid';
import { Checkpoint } from '../components/checkpoint';
import { Crate } from '../components/crate';

export const Scene = () => {
    const rng = useRandom();

    usePhysicsWorld2d({
        gravity: {
            x: 0,
            y: 340
        }
    });

    useSpawn(Solid)(Settings.WIDTH / 2, Settings.HEIGHT - Settings.WALL / 2, Settings.WIDTH, Settings.WALL);
    useSpawn(Solid)(Settings.WALL / 2, Settings.HEIGHT / 2, Settings.WALL, Settings.HEIGHT);
    useSpawn(Solid)(Settings.WIDTH - Settings.WALL / 2, Settings.HEIGHT / 2, Settings.WALL, Settings.HEIGHT);
    useSpawn(Checkpoint, 'Checkpoint')();

    for (let i = 0;i < 9;i++) {
        const size = rng.rand(20, 30);

        useSpawn(Crate)(rng.rand(Settings.WALL + 12 + size / 2, Settings.WIDTH - Settings.WALL - 42), -size / 2 - i * 52, size);
    }

    return createScene();
};
```

`settings.ts`:

```ts
import { getColor } from 'nacatamalon';

// A solver that pushes things apart is only half of gameplay physics. The other half is
// being TOLD about a contact: the bullet hit the tank, the player reached the checkpoint.
//
// Every body has two listeners for that, called like the rest of the engine's on-methods:
//
//     body.onEnter((other) => ...)   // started touching
//     body.onExit((other) => ...)    // stopped touching
//
// The payload is THE OTHER OBJECT, which is what makes filtering possible: "was that the
// checkpoint or just another crate?" is a question about identity, and the object is the
// identity.
//
// Three details worth knowing:
//
//   sensor: true makes a collider DETECT without RESOLVING. Things pass straight through
//   it. That is the trigger volume: a checkpoint, a pickup, a damage zone. A solid body
//   reports its contacts too, it just also stops you.
//
//   Only one side has to listen: the crate hears the trigger, and the trigger needs no code.
//
//   The body is reached through the world and not kept from the call that declared it: the
//   engine hands back what the object is MADE OF, and the simulated body is the adapter's.
//   It appears as the scene is built and the WebAssembly is still loading, so it is waited
//   for rather than assumed.

export const WIDTH = 480;
export const HEIGHT = 380;
export const WALL = 12;
export const ZONE_Y = 170;
export const ZONE_H = 74;
export const FALLING = getColor('#ff6b6b');
// above the zone, untouched
export const INSIDE = getColor('#ffd93d');
// currently overlapping the checkpoint
export const PASSED = getColor('#4cff91');
```
