# Tween control

> A tween is declared once and played as many times as you like: play it, pause it, stop it, send it to the end or back to the start.

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

A tween is declared once and played as many times as you like. `play()` starts it from the beginning, over or halfway. `pause()` and `resume()` freeze it and pick it up where it stopped, `stop()` leaves it where it is (only `onStop` hears it), `finish()` sends it to the end value and announces it with `onEnd`, and `reset()` puts it back where the play started.

`playing` is true from `play()` until it ends or is stopped.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Scene } from './scenes/demo';
import { WIDTH, HEIGHT } from './settings';

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

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

`components/rail.ts`:

```ts
import { createSprite, createText, getColor, useTween } from 'nacatamalon';
import { easeOutElastic } from 'nacatamalon/math';
import { START, END, STATES, DURATION, WIDTH } from '../settings';

export const Rail = () => {
    const tween = useTween();

    // The rail: the whole trip, drawn, so a ball that stops halfway can be seen stopping halfway.
    createSprite({
        tint: '#1c1c30',
        width: END - START,
        height: 2,
        transform: {
            x: (START + END) / 2,
            y: 112
        },
    });

    const ball = createSprite({
        tint: getColor(STATES.idle.color),
        width: 26,
        height: 26,
        transform: {
            x: START,
            y: 100
        },
    });

    const lamp = createSprite({
        tint: getColor(STATES.idle.color),
        width: 120,
        height: 10,
        transform: {
            x: WIDTH / 2,
            y: 180
        },
    });

    const label = createText({
        text: STATES.idle.label,
        anchor: {
            x: 0.5,
            y: 0
        },
        tint: getColor(STATES.idle.color),
        transform: {
            x: WIDTH / 2,
            y: 200
        },
    });

    createText({
        text: 'SPACE PLAY  P PAUSE  S STOP  F FINISH  R RESET',
        anchor: {
            x: 0.5,
            y: 0
        },
        tint: '#6a6a8a',
        transform: {
            x: WIDTH / 2,
            y: 290
        },
    });

    const setState = (state: keyof typeof STATES) => {
        const { label: word, color } = STATES[state];

        label.text = word;
        label.tint = getColor(color);
        ball.tint = getColor(color);
        lamp.tint = getColor(color);
    };

    // The ball's x, from where it is to the far end. Declared once: nothing moves until it is
    // played, and every play makes the same trip from the same start.
    const roll = tween({
        target: ball,
        to: {
            transform: {
                x: END
            }
        },
        duration: DURATION,
        ease: easeOutElastic,
    });

    // The tween says how it ended, so the keys below only press its buttons.
    roll.onEnd(() => setState('done'));
    roll.onStop(() => setState('stopped'));

    return {
        roll,
        setState
    };
};
```

`hooks/use_playback_controls.ts`:

```ts
import { useKeyboard, useUpdate } from 'nacatamalon';
import type { Rail } from '../components/rail';

export const usePlaybackControls = ({ roll, setState }: ReturnType<typeof Rail>) => {
    const keyboard = useKeyboard();
    let paused = false;

    useUpdate(() => {
        // justPressed is true for exactly one frame per press, so holding a key does nothing and
        // there is no timer here counting down to the next allowed press.
        if (keyboard.justPressed(' ')) {
            // Over or halfway, it starts again from the beginning: the ball goes back first.
            roll.play();
            paused = false;
            setState('running');

            return;
        }

        if (keyboard.justPressed('r')) {
            // Back to the start; onStop says so if it was still going.
            roll.reset();
            paused = false;
            setState('idle');

            return;
        }

        // Nothing else to press while it is not playing.
        if (!roll.playing) {
            return;
        }

        if (keyboard.justPressed('p')) {
            paused = !paused;

            if (paused) {
                roll.pause();
            } else {
                roll.resume();
            }

            setState(paused ? 'paused' : 'running');
        }

        if (keyboard.justPressed('s')) {
            // onStop says STOPPED.
            roll.stop();
            paused = false;
        }

        if (keyboard.justPressed('f')) {
            // Jumps to the far end and fires onEnd, so it says FINISHED: finish is an ending,
            // stop is not.
            roll.finish();
            paused = false;
        }
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useSpawn } from 'nacatamalon';
import { Rail } from '../components/rail';
import { usePlaybackControls } from '../hooks/use_playback_controls';

export const Scene = () => {
    const rail = useSpawn(Rail)();

    usePlaybackControls(rail.api);

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
export const DURATION = 2.2;
export const START = 40;
export const END = 424;

// Each state has a word and a colour, and the label, the ball and the lamp under the rail always
// agree on it.
export const STATES = {
    idle:      {
        label: 'IDLE',
        color: '#3a3a55'
    },
    running:   {
        label: 'RUNNING',
        color: '#ffffff'
    },
    paused:    {
        label: 'PAUSED',
        color: '#ffd926'
    },
    stopped:   {
        label: 'STOPPED',
        color: '#ff4033'
    },
    done:      {
        label: 'FINISHED',
        color: '#33ff8c'
    },
};
```
