# Attach a script

> A behaviour with a name, written once and attached to three objects with different settings.

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

A script is a behaviour with a name. It is written once, on its own, and attached to an object by that name: the three guards here run the same `patrol` at different speeds and distances, and the object never mentions what it does. The settings are declared by the code, because nothing outside a function can know what its variables are, and each carries a default, so an object that sets only one still gets both.

**Why a name and not a function.** The name is what a saved scene can hold: a file cannot carry code, so an editor attaching a behaviour writes down `patrol` and its settings, and the engine looks it up when the scene opens. The same indirection lets a behaviour gain a setting later without invalidating every scene saved before it.

## Code

`index.ts`:

```ts
import { registerPatrol } from './scripts/patrol';
import { createGame } from 'nacatamalon';
import { WIDTH, HEIGHT } from './settings';
import { Level } from './scenes/demo';

registerPatrol();

const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: '#14121c',
});

// Declare Scenes
game({
    Level
});
```

`components/guard.ts`:

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

import type { TPatrolProps } from '../scripts/patrol';

export const Guard = ({ y, colour, props }: { y: number; colour: string; props: Partial<TPatrolProps> }) => {
    createSprite({
        tint: getColor(colour),
        width: 26,
        height: 26,
        transform: {
            x: 150,
            y: y
        }
    });
    useScript('patrol', props);
};
```

`scenes/demo.ts`:

```ts
import { createScene, createText, useLoadBitmapFont, useSpawn } from 'nacatamalon';
import * as Settings from '../settings';

import { Guard } from '../components/guard';

export const Level = () => {
    const font = useLoadBitmapFont(Settings.FONT);

    const label = (text: string, y: number) => createText({
        text,
        font,
        style: {
            fontSize: 8
        },
        tint: '#8fa4c4',
        transform: {
            x: 16,
            y: y
        },
    });

    // Nothing set: both settings come from what the behaviour declared.
    label('DEFAULTS', 44);
    useSpawn(Guard)({
        y: 60,
        colour: '#5bd75b',
        props: {
        }
    });

    // The same behaviour, three times as fast. This is what the settings exist for.
    label('SPEED 120', 104);
    useSpawn(Guard)({
        y: 120,
        colour: '#e5c93b',
        props: {
            speed: 120
        }
    });

    // Only one of the two set: the other still comes from the default.
    label('RANGE 130', 164);
    useSpawn(Guard)({
        y: 180,
        colour: '#e5533b',
        props: {
            range: 130
        }
    });

    return createScene();
};
```

`scripts/patrol.ts`:

```ts
import { registerScript, useUpdate } from 'nacatamalon';

export type TPatrolProps = { speed: number; range: number };
export const registerPatrol = () => {
    registerScript<TPatrolProps>('patrol', (self, props) => {
    // A behaviour reaches for what its object carries. If there is nothing to move, give up
    // quietly: one badly set up object must never take a whole scene down.
        const [sprite] = self.drawables;

        if (sprite === undefined) {
            return;
        }

        const start = sprite.transform.x;
        let dir = 1;

        useUpdate((delta) => {
            sprite.transform.x += props.speed * dir * delta;

            if (Math.abs(sprite.transform.x - start) >= props.range) {
                dir = -dir;
                // Put back on the line, so a slow frame cannot leave it drifting outwards.
                sprite.transform.x = start + Math.sign(sprite.transform.x - start) * props.range;
            }
        });
    }, [
    // Declaring a setting is what makes it editable, and what gives it a value when nobody sets it.
        {
            key: 'speed',
            label: 'Speed (px/s)',
            type: 'number',
            default: 40,
            min: 0,
            step: 10
        },
        {
            key: 'range',
            label: 'How far',
            type: 'number',
            default: 60,
            min: 0,
            step: 10
        },
    ]);
};
```

`settings.ts`:

```ts
export const WIDTH = 340;
export const HEIGHT = 220;
export const FONT = {
    json: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.json',
    atlas: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.png',
};
```
