# Character in a retro world

> The platformer character in a retro world: ladders and ledges, crates it pushes, a lift it rides, and an enemy that looks ahead with castRetroRay2d.

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

The platformer's character, `useTileBody2d`, in a scene with a retro world: it is then one of the world's bodies. It still walks the map as it does alone, with ledges dropped through with **down**, ladders climbed with **up** and slopes, and now it also pushes the crates, rides the lift, and cannot push the enemy out of its way.

The enemy turns round by itself with `castRetroRay2d`: a ray down just ahead of its feet finds no floor at the end of its ledge, and a ray ahead finds the wall. **Arrows** to move, **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');
```

`art/tiles.ts`:

```ts
import { sheetFromRows } from 'nacatamalon/pixels';

// The tiles of the map, eight pixels a side, painted from rows of letters.
export const paintTiles = () => sheetFromRows({
    ground: ['gggggggg', 'gGggGggG', 'GdGddGdG', 'dddddddd', 'dDdddddD', 'dddDdddd', 'dddddddd', 'DdddddDd'],
    earth: ['dddddddd', 'dDdddddD', 'dddDdddd', 'dddddddd', 'ddddDddd', 'dDdddddd', 'ddddddDd', 'dddddddd'],
    ledge: ['ssssssss', 'SSSSSSSS', '.S....S.', '.S....S.', '........', '........', '........', '........'],
    up: ['.......g', '......gG', '.....gGd', '....gGdd', '...gGddd', '..gGdddd', '.gGddddd', 'gGdddddd'],
    down: ['g.......', 'Gg......', 'dGg.....', 'ddGg....', 'dddGg...', 'ddddGg..', 'dddddGg.', 'ddddddGg'],
    belt: ['SSSSSSSS', 'YsYsYsYs', 'SSSSSSSS', 'S.S.S.S.', 'SSSSSSSS', 'dddddddd', 'dDdddddD', 'dddddddd'],
    coin: ['........', '..yyyy..', '.yYYYYy.', '.yYyyYy.', '.yYyyYy.', '.yYYYYy.', '..yyyy..', '........'],
    ladder: ['Y......Y', 'YyyyyyyY', 'Y......Y', 'Y......Y', 'Y......Y', 'YyyyyyyY', 'Y......Y', 'Y......Y'],
}, {
    g: '#6abe30',
    G: '#37946e',
    d: '#8f563b',
    D: '#663931',
    s: '#9badb7',
    S: '#696a6a',
    y: '#fbf236',
    Y: '#df7126',
});
```

`components/crate.ts`:

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

export const Crate = (x: number, y: number, size: number) => {
    createSprite({
        tint: '#df7126',
        width: size,
        height: size,
        transform: {
            x,
            y
        }
    });
    useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'rect',
            width: size,
            height: size
        },
        // The big one is hard work.
        mass: size > 8 ? 3 : 1,
    });
};
```

`components/enemy.ts`:

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

// Walks back and forth on its ledge, looking where it goes: no floor ahead, or a wall, and it turns.
// Not pushable, so the hero cannot shove it off.
export const Enemy = () => {
    const sprite = createSprite({
        tint: '#ff6b6b',
        width: 8,
        height: 8,
        transform: {
            x: 160,
            y: 60
        }
    });
    useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'rect',
            width: 8,
            height: 8
        },
        pushable: false,
    });

    const self = useSelf();
    const body = getRetroBody2d(self);
    let facing = 1;

    useUpdate(() => {
        if (body === null || !body.touching.down) {
            return;
        }
        const x = sprite.transform.x;
        const y = sprite.transform.y;
        const floor = castRetroRay2d(self, { x: x + facing * 6, y }, { x: 0, y: 1 }, { maxDistance: 8 });
        const wall = castRetroRay2d(self, { x, y }, { x: facing, y: 0 }, { maxDistance: 6 });
        if (floor === null || wall !== null) {
            facing = -facing;
        }
        body.velocity.x = facing * 25;
    });
};
```

`components/hero.ts`:

```ts
import { createSprite, useKeyboard, useTileBody2d, useUpdate } from 'nacatamalon';

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

// The same character a game on the maps alone writes. In a retro scene it is a body of the world.
export const Hero = () => {
    const sprite = createSprite({
        tint: '#5db6ff',
        width: 6,
        height: 12,
        transform: {
            x: 40,
            y: 130
        }
    });
    const body = useTileBody2d({
        width: 6,
        height: 12
    });
    const keys = useKeyboard();

    useUpdate(() => {
        const walk = (keys.isDown('ArrowRight') ? 1 : 0) - (keys.isDown('ArrowLeft') ? 1 : 0);
        body.velocity.x = walk * Settings.WALK;
        if (walk !== 0) {
            sprite.flipX = walk < 0;
        }
        if ((keys.justPressed('z') || keys.justPressed(' ')) && body.isOnGround) {
            body.velocity.y = -Settings.JUMP;
        }
        if (keys.justPressed('ArrowDown') && body.isOnOneWay && !body.isOnLadder) {
            body.dropThrough();
        }
        // Onto a ladder with up in front of it, or with down standing on its top.
        const up = keys.isDown('ArrowUp') && !body.isOnOneWay;
        const down = keys.isDown('ArrowDown') && body.isOnOneWay;
        if (body.isOnLadder && (up || down)) {
            body.climbing = true;
        }
        if (body.climbing) {
            body.velocity.y = keys.isDown('ArrowUp') ? -50 : keys.isDown('ArrowDown') ? 50 : 0;
        }
    });
};
```

`components/lift.ts`:

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

// Up and down between the ground and the high ledge, driven by its velocity.
export const Lift = () => {
    const sprite = createSprite({
        tint: '#ffd93d',
        width: 24,
        height: 4,
        transform: {
            x: 20,
            y: 134
        }
    });
    useRetroBody2d({
        body: 'kinematic',
        collider: {
            shape: 'rect',
            width: 24,
            height: 4
        }
    });
    const body = getRetroBody2d(useSelf());
    let going = -1;

    useUpdate(() => {
        if (body === null) {
            return;
        }
        if (sprite.transform.y <= 50) {
            going = 1;
        }
        if (sprite.transform.y >= 134) {
            going = -1;
        }
        body.velocity.y = going * 30;
    });
};
```

`components/world.ts`:

```ts
import { createSpriteAtlas, createTilemap } from 'nacatamalon';
import { createPixelTexture } from 'nacatamalon/pixels';

import { paintTiles } from '../art/tiles';
import { ROWS, LEGEND } from '../data/level';

export const World = () => {
    const tiles = paintTiles();
    const { frames } = tiles;

    return createTilemap({
        doc: {
            cell: 8,
            width: ROWS[0].length,
            height: ROWS.length,
            tiles: {
                1: { frame: frames.ground, solid: true },
                2: { frame: frames.earth, solid: true },
                3: { frame: frames.ledge, oneWay: true },
                4: { frame: frames.up, slope: [0, 1] },
                5: { frame: frames.down, slope: [1, 0] },
                8: { frame: frames.ladder, ladder: true },
                // The top rung is a ledge too, so it can be stood on.
                9: { frame: frames.ladder, ladder: true, oneWay: true },
            },
            layers: [
                {
                    name: 'ground',
                    order: 'under',
                    data: ROWS.flatMap((row) => [...row].map((character) => LEGEND[character] ?? 0)),
                }
            ],
        },
        atlas: createSpriteAtlas({
            texture: createPixelTexture(tiles.pixels),
            columns: tiles.columns
        }),
    });
};
```

`data/level.ts`:

```ts
// `#` ground, `=` earth, `-` a ledge, `H` a ladder, `T` the ladder's top (a ladder you stand on),
// `u` and `d` slopes.
export const LEGEND: Record<string, number> = { '#': 1, '=': 2, '-': 3, 'u': 4, 'd': 5, 'H': 8, 'T': 9 };

export const ROWS = [
    '==============================',
    '=............................=',
    '=............................=',
    '=............................=',
    '=............................=',
    '=............................=',
    '=....-------.................=',
    '=............................=',
    '=............................=',
    '=..............T-------......=',
    '=..............H.............=',
    '=..............H.............=',
    '=..............H.............=',
    '=..............H.............=',
    '=..............H.........ud..=',
    '=..............H........u==d.=',
    '=..............H.......u====d=',
    '##############################',
    '==============================',
    '==============================',
];
```

`scenes/demo.ts`:

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

import { World } from '../components/world';
import { Hero } from '../components/hero';
import { Crate } from '../components/crate';
import { Lift } from '../components/lift';
import { Enemy } from '../components/enemy';

export const Scene = () => {
    useCamera2d({
        zoom: 2
    });
    useRetroWorld2d({
        gravity: {
            x: 0,
            y: 600
        }
    });

    useSpawn(World)();
    useSpawn(Lift, 'Lift')();
    const crate = useSpawn(Crate, 'Crate');
    crate(70, 132, 8);
    crate(90, 130, 12);
    crate(170, 120, 8);
    useSpawn(Enemy, 'Enemy')();
    useSpawn(Hero, 'Hero')();

    createText({
        text: 'ARROWS, Z TO JUMP',
        transform: {
            x: 120,
            y: 16
        },
        anchor: {
            x: 0.5,
            y: 0
        }
    });

    return createScene();
};
```

`settings.ts`:

```ts
// The platformer's character, `useTileBody2d`, in a scene with a retro world: it is then one of the
// world's bodies. It still walks the map as it does alone (ledges you drop through with down,
// ladders you climb with up, slopes), and now it also pushes the crates, rides the lift, and the
// enemy cannot be pushed out of its way.
//
// The enemy turns round by itself with `castRetroRay2d`: a ray down just ahead of its feet finds no
// floor at the end of its ledge, and a ray ahead finds the wall.

export const WIDTH = 480;
export const HEIGHT = 320;
export const WALK = 70;
export const JUMP = 230;
```
