# Debug mode

> The engine's debug mode over a retro level: colliders, hitboxes, tiles and rays; and the retro world's timeScale for slow motion and pause.

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

The debug mode, which every game has: `debug: true` in `createGame`, or `useGame().setDebugEnabled(...)` while it runs, here on **F1**. It draws over each scene what it is made of: every collider in the colour of how it moves (grey still, green dynamic, yellow driven, blue a sensor, dark switched off) and where it is going, the hitboxes, the tiles that stop things (orange walls and slopes, purple ledges), the rays cast in the frame, such as the enemy's looking for floor and walls, and the edges of a world that has them.

The retro world keeps its own time too: **T** for slow motion and **P** to pause it, with `timeScale` on the world `useRetroWorld2d` gave back. The rest of the game goes on. **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',
    // Seen from the start: F1 turns it off and on.
    debug: true,
});

// 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/coin.ts`:

```ts
import { createSprite, destroy, useCollisionWith, useHitbox, useSelf, useTransform } from 'nacatamalon';

// A coin with a hitbox, the pink outline: taken when the hero, by its tag, touches it.
export const Coin = (x: number, y: number) => {
    useTransform({
        x,
        y
    });
    createSprite({
        tint: '#fbf236',
        width: 5,
        height: 5
    });
    useHitbox({
        width: 7,
        height: 7
    });
    const self = useSelf();
    useCollisionWith('hero', () => destroy(self), { when: 'start' });
};
```

`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, useGame, useKeyboard, useRetroWorld2d, useSpawn, useUpdate } 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';
import { Coin } from '../components/coin';

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

    useSpawn(World)();
    useSpawn(Lift, 'Lift')();
    const crate = useSpawn(Crate, 'Crate');
    crate(70, 132, 8);
    crate(90, 130, 12);
    useSpawn(Enemy, 'Enemy')();
    const coin = useSpawn(Coin, 'Coin');
    for (let i = 0; i < 5; i++) coin(48 + i * 10, 40);
    useSpawn(Hero, { name: 'Hero', tags: ['hero'] })();

    // The camera shows the level twice as big: the label is half size, to be read at the usual size.
    const label = createText({
        text: '',
        transform: {
            x: 120,
            y: 6,
            scaleX: 0.5,
            scaleY: 0.5
        },
        anchor: {
            x: 0.5,
            y: 0
        }
    });
    const game = useGame();
    const keys = useKeyboard();
    useUpdate(() => {
        if (keys.justPressed('F1')) game.setDebugEnabled(!game.isDebugEnabled());
        if (keys.justPressed('t')) world.timeScale = world.timeScale === 1 ? 0.25 : 1;
        if (keys.justPressed('p')) world.timeScale = world.timeScale === 0 ? 1 : 0;
        const time = world.timeScale === 0 ? 'PAUSED' : world.timeScale < 1 ? 'SLOW' : 'NORMAL';
        label.text = `F1 DEBUG ${game.isDebugEnabled() ? 'ON' : 'OFF'}   T SLOW   P PAUSE   ${time}`;
    });

    return createScene();
};
```

`settings.ts`:

```ts
// The debug mode, which every game has: `debug: true` in createGame, or
// `useGame().setDebugEnabled(...)` while it runs, here on F1. It draws over each scene what it is made
// of: every collider in the colour of how it moves (grey still, green dynamic, yellow driven, blue a
// sensor, dark switched off) and where it is going, the hitboxes, the tiles that stop things (orange
// walls and slopes, purple ledges), the rays cast in the frame (the enemy's, looking for floor and
// walls), and the edges of a world that has them.
//
// The retro world keeps its own time too: T for slow motion, P to pause it (`timeScale` on the world
// useRetroWorld2d gave back). The rest of the game goes on.

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