# Grow and shrink

> A hero that a mushroom makes big and a hit makes small: its collider changes with its picture, its feet stay on the floor, and it grows only where it fits.

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

A body whose size is part of the game: the hero is small, a mushroom makes it big, and a hit while big makes it small again. Changing `record.collider.width` and `height` is all it takes: the body is that size from the next step on, a body standing when it changes keeps its feet where they were, and one that grew into a wall comes out of it. `isRetroAreaFree2d` lets it grow only where the big body fits, so never into a ceiling.

Hurt, it goes through the walkers for a moment with `collidesIf`, blinking. `onEnter` with `contact.side` tells a stomp (landing from above) from a hit. The tunnel on the right is lower than the big hero: only the small one goes through. **Arrows** to move, **up** or **Z** to jump.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { installRetroPhysics2d } from 'nacatamalon/retro-physics2d';

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

// The one line that makes retro bodies move. Nothing to load: no WebAssembly, no waiting.
installRetroPhysics2d();

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

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

`components/hero.ts`:

```ts
import { createSprite, useKeyboard, useRetroBody2d, useSelf, useUpdate } from 'nacatamalon';
import { getRetroBody2d, isRetroAreaFree2d } from 'nacatamalon/retro-physics2d';
import type { TGameObject } from 'nacatamalon';

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

type TSize = { width: number; height: number };
type TWalker = TGameObject<{ stomp(): void }>;

// The hero: small or big, and its body always the size of its picture. `say` puts a line on screen.
export const Hero = (say: (line: string) => void) => {
    const sprite = createSprite({
        tint: '#5db6ff',
        width: Settings.SMALL.width,
        height: Settings.SMALL.height,
        transform: {
            x: Settings.START.x,
            y: Settings.START.y
        }
    });
    const record = useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'rect',
            width: Settings.SMALL.width,
            height: Settings.SMALL.height
        },
        drag: Settings.DRAG,
        maxSpeed: Settings.MAX,
    });

    const self = useSelf();
    const body = getRetroBody2d(self)!;
    const keys = useKeyboard();
    let big = false;
    let growing = false;
    let safe = 0;

    // The picture and the collider change together. The world does the rest: standing, the hero
    // keeps its feet on the floor.
    const resize = (size: TSize) => {
        sprite.width = size.width;
        sprite.height = size.height;
        record.collider = { shape: 'rect', width: size.width, height: size.height };
    };

    // While it is hurt, the walkers are not there for it.
    body.collidesIf((other) => !(safe > 0 && other.name === 'Walker'));

    const hurt = () => {
        if (safe > 0) {
            return;
        }
        if (big) {
            big = false;
            resize(Settings.SMALL);
            safe = Settings.SAFE;
            say('OUCH! SMALL AGAIN');
            return;
        }
        // Moving the object moves its body: back to the start, still.
        sprite.transform.x = Settings.START.x;
        sprite.transform.y = Settings.START.y;
        body.setLinearVelocity(0, 0);
        safe = Settings.SAFE;
        say('BACK TO THE START');
    };

    body.onEnter((other, contact) => {
        if (other.name !== 'Walker' || safe > 0) {
            return;
        }
        // The walker is under it: it came down on top.
        if (contact.side === 'down') {
            (other as TWalker).api.stomp();
            body.velocity.y = -Settings.JUMP * 0.6;
            return;
        }
        hurt();
    });

    useUpdate((dt) => {
        const walk = (keys.isDown('ArrowRight') ? 1 : 0) - (keys.isDown('ArrowLeft') ? 1 : 0);
        body.acceleration.x = walk * Settings.RUN;
        if (walk !== 0) {
            sprite.flipX = walk < 0;
        }
        const jump = keys.justPressed('ArrowUp') || keys.justPressed('z') || keys.justPressed(' ');
        if (jump && body.blocked.down) {
            body.velocity.y = -Settings.JUMP;
        }
        const held = keys.isDown('ArrowUp') || keys.isDown('z') || keys.isDown(' ');
        if (!held && body.velocity.y < -Settings.JUMP * 0.4) {
            body.velocity.y = -Settings.JUMP * 0.4;
        }

        // It grows as soon as the big body fits where it stands: feet where they are, head higher.
        if (growing) {
            const feet = sprite.transform.y + Settings.SMALL.height / 2;
            const room = isRetroAreaFree2d(self, {
                x: sprite.transform.x - Settings.BIG.width / 2,
                y: feet - Settings.BIG.height,
                width: Settings.BIG.width,
                height: Settings.BIG.height
            });
            if (room) {
                growing = false;
                big = true;
                resize(Settings.BIG);
                say('BIG!');
            } else {
                say('NO ROOM TO GROW HERE');
            }
        }

        safe = Math.max(0, safe - dt);
        sprite.visible = safe === 0 || Math.floor(safe * 12) % 2 === 0;
    });

    return {
        grow: () => {
            if (big) {
                return;
            }
            growing = true;
        },
    };
};
```

`components/mushroom.ts`:

```ts
import { createSprite, destroy, useRetroBody2d, useSelf } from 'nacatamalon';
import { getRetroBody2d } from 'nacatamalon/retro-physics2d';

// A sensor: it stops nothing, and tells when the hero touches it.
export const Mushroom = (x: number, y: number, eaten: () => void) => {
    createSprite({
        tint: '#ffd93d',
        width: 10,
        height: 10,
        transform: {
            x,
            y
        }
    });
    useRetroBody2d({
        body: 'static',
        sensor: true,
        collider: {
            shape: 'rect',
            width: 10,
            height: 10
        },
    });

    const self = useSelf();
    getRetroBody2d(self)!.onEnter((other) => {
        if (other.name === 'Hero') {
            destroy(self);
            eaten();
        }
    });
};
```

`components/solid.ts`:

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

// A wall or the floor: a body that never moves, the size of its picture.
export const Solid = (x: number, y: number, w: number, h: number) => {
    createSprite({
        tint: '#2a2a3a',
        width: w,
        height: h,
        transform: {
            x,
            y
        }
    });
    useRetroBody2d({
        body: 'static',
        collider: {
            shape: 'rect',
            width: w,
            height: h
        }
    });
};
```

`components/walker.ts`:

```ts
import { createSprite, destroy, useRetroBody2d, useSelf, useUpdate } from 'nacatamalon';
import { getRetroBody2d } from 'nacatamalon/retro-physics2d';

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

// Walks until something stops it, then turns round. Nothing pushes it: the hero bumps into it.
export const Walker = (x: number, y: number, stomped: () => void) => {
    createSprite({
        tint: '#ff6b6b',
        width: Settings.WALKER.width,
        height: Settings.WALKER.height,
        transform: {
            x,
            y
        }
    });
    useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'rect',
            width: Settings.WALKER.width,
            height: Settings.WALKER.height
        },
        pushable: false,
    });

    const self = useSelf();
    const body = getRetroBody2d(self)!;
    let way = -1;

    useUpdate(() => {
        if (body.blocked.left) {
            way = 1;
        } else if (body.blocked.right) {
            way = -1;
        }
        body.velocity.x = way * Settings.WALKER.speed;
    });

    return {
        stomp: () => {
            destroy(self);
            stomped();
        },
    };
};
```

`scenes/demo.ts`:

```ts
import { createScene, createText, useRetroWorld2d, useSpawn, useTimer } from 'nacatamalon';

import * as Settings from '../settings';
import { Solid } from '../components/solid';
import { Hero } from '../components/hero';
import { Walker } from '../components/walker';
import { Mushroom } from '../components/mushroom';

export const Scene = () => {
    useRetroWorld2d({
        gravity: {
            x: 0,
            y: 1100
        }
    });
    const timer = useTimer();

    const solid = useSpawn(Solid, 'Wall');
    solid(Settings.WIDTH / 2, Settings.HEIGHT - Settings.WALL / 2, Settings.WIDTH, Settings.WALL);
    solid(Settings.WALL / 2, Settings.HEIGHT / 2, Settings.WALL, Settings.HEIGHT);
    solid(Settings.WIDTH - Settings.WALL / 2, Settings.HEIGHT / 2, Settings.WALL, Settings.HEIGHT);
    solid(Settings.STEP.x, Settings.FLOOR - Settings.STEP.height / 2, Settings.STEP.width, Settings.STEP.height);
    for (const [x, y, width] of Settings.PLATFORMS) {
        solid(x, y, width, 10);
    }
    // The wall with the low tunnel under it.
    const top = Settings.FLOOR - Settings.TUNNEL.gap;
    solid(Settings.TUNNEL.x, top / 2, Settings.TUNNEL.width, top);

    const said = createText({
        text: 'EAT A MUSHROOM',
        transform: {
            x: Settings.MIDDLE,
            y: 40
        },
        anchor: {
            x: 0.5,
            y: 0
        }
    });
    const hero = useSpawn(Hero, 'Hero')((line: string) => {
        said.text = line;
    });

    // Each mushroom grows back a while after it is eaten, and each walker comes back after a stomp.
    const mushroom = useSpawn(Mushroom, { name: 'Mushroom', parent: 'scene' });
    const plant = (x: number, y: number) => mushroom(x, y, () => {
        hero.api.grow();
        timer.after(5, () => plant(x, y));
    });
    Settings.MUSHROOMS.forEach(([x, y]) => plant(x, y));

    const walker = useSpawn(Walker, { name: 'Walker', parent: 'scene' });
    const send = (x: number, y: number) => walker(x, y, () => {
        timer.after(Settings.WALKER.back, () => send(x, y));
    });
    Settings.WALKERS.forEach(([x, y]) => send(x, y));

    createText({
        text: 'ARROWS, Z TO JUMP',
        transform: {
            x: Settings.MIDDLE,
            y: 20
        },
        anchor: {
            x: 0.5,
            y: 0
        }
    });
    createText({
        text: 'SMALL ONLY',
        transform: {
            x: (Settings.TUNNEL.x + Settings.WIDTH - Settings.WALL) / 2 + Settings.TUNNEL.width / 4,
            y: Settings.FLOOR - 50
        },
        anchor: {
            x: 0.5,
            y: 0
        }
    });

    return createScene();
};
```

`settings.ts`:

```ts
// A body whose size is part of the game: the hero is small, a mushroom makes it big, and a hit while
// big makes it small again. Its collider changes with its picture, and nothing else is needed:
//
//   record.collider.width / height: the body is that size from the next step on. A body standing
//   when it changes keeps its feet where they were, so it grows up from the floor and shrinks down
//   to it, and comes out of any wall it grew into.
//   isRetroAreaFree2d: it grows only where the big body fits, so never into a ceiling.
//   collidesIf: hurt, it goes through the walkers for a moment, blinking.
//   onEnter with contact.side: landing on a walker ('down') stomps it; any other side hurts.
//
// The tunnel on the right is lower than the big hero: only the small one goes through.

export const WIDTH = 480;
export const HEIGHT = 320;
export const WALL = 12;
export const FLOOR = HEIGHT - WALL;
export const SMALL = { width: 12, height: 14 };
export const BIG = { width: 14, height: 28 };
export const START = { x: 40, y: FLOOR - SMALL.height / 2 };
export const RUN = 900;
export const DRAG = 700;
export const MAX = { x: 130, y: 480 };
export const JUMP = 380;
export const SAFE = 1.5;
export const WALKER = { width: 14, height: 12, speed: 40, back: 4 };
// A tunnel 20 pixels high under the wall: room for the small hero, not the big one.
export const TUNNEL = { x: 330, width: 40, gap: 20 };
// A jump rises about 65 pixels (JUMP squared over twice the gravity): each platform is within one.
export const PLATFORMS: Array<[number, number, number]> = [
    // x, y, width
    [130, 265, 80],
    [230, 220, 70],
];
export const MUSHROOMS: Array<[number, number]> = [
    [130, 254],
    [230, 209],
];
// A step by the start that the walkers turn back at and the hero jumps over.
export const STEP = { x: 80, width: 12, height: 14 };
// Where the texts go: the middle of the part left of the tunnel's wall.
export const MIDDLE = (WALL + TUNNEL.x - TUNNEL.width / 2) / 2;
export const WALKERS: Array<[number, number]> = [
    [160, FLOOR - WALKER.height / 2],
    [260, FLOOR - WALKER.height / 2],
];
```
