# Top-down shooter

> A top-down shooter: no gravity, fast shots against thin walls, named layers, and setLayers to ghost the ship after a hit.

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

Seen from above, so the world has no gravity and everything moves only as it is told. The ship is driven by `acceleration`, slowed by `drag` once let go and held to `maxSpeed`. The shots go at 600 pixels a second and still stop at a wall two pixels thin, because a retro body moves in pieces no longer than the smallest thing it could miss.

Named layers keep shots from hitting each other or the ship. Two bodies meet only if each one meets the other's layer, so the ship leaving `'enemy'` out of what it meets is enough. Hit, the ship blinks for a moment with `setLayers`, meeting only the walls. **Arrows** or **WASD** to move, **click** to shoot.

## Code

`index.ts`:

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

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

installRetroPhysics2d();

const game = createGame('#app', {
    width: Settings.WIDTH,
    height: Settings.HEIGHT,
    background: '#0a0a18',
    // The layers by name: a body says what it is on and what it meets with these.
    physicsLayers: Settings.LAYERS,
});

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

`art/ball.ts`:

```ts
import { createPixels, createPixelTexture, fillCircle } from 'nacatamalon/pixels';

// A white disc, painted once for the scene and tinted per ball. Odd-sized so it has a middle
// pixel and comes out round.
export const paintBall = (size: number) => {
    const side = size | 1;
    const pixels = createPixels(side, side);
    fillCircle(pixels, (side - 1) / 2, (side - 1) / 2, (side - 1) / 2, '#ffffff');
    return createPixelTexture(pixels);
};
```

`components/enemy.ts`:

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

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

export const Enemy = (x: number, y: number, ship: TGameObject, gone: () => void) => {
    // Told when it is destroyed, so the scene knows how many are left.
    useCleanup(gone);

    const sprite = createSprite({
        tint: '#ff6b6b',
        width: Settings.ENEMY.size,
        height: Settings.ENEMY.size,
        transform: {
            x,
            y
        }
    });
    useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'rect',
            width: Settings.ENEMY.size,
            height: Settings.ENEMY.size
        },
        gravityScale: 0,
        layer: 'enemy',
        collidesWith: ['world', 'ship', 'shot', 'enemy'],
    });

    const self = useSelf();
    const body = getRetroBody2d(self);

    // Straight at the ship, always: the walls and the other enemies are what get in the way.
    useUpdate(() => {
        if (body === null || ship.destroyed) {
            return;
        }
        const at = ship.drawables[0] as { transform: { x: number; y: number } };
        const dx = at.transform.x - sprite.transform.x;
        const dy = at.transform.y - sprite.transform.y;
        const far = Math.hypot(dx, dy) || 1;
        body.setLinearVelocity(dx / far * Settings.ENEMY.speed, dy / far * Settings.ENEMY.speed);
    });
};
```

`components/ship.ts`:

```ts
import { createSprite, getColor, useKeyboard, usePointer, useRetroBody2d, useSelf, useSpawn, useTimer, useUpdate } from 'nacatamalon';
import { getRetroBody2d } from 'nacatamalon/retro-physics2d';
import type { TTexture } from 'nacatamalon';

import * as Settings from '../settings';
import { Shot } from './shot';

const SOLID = getColor('#5db6ff');
const GHOST = getColor('#5db6ff55');

export const Ship = (picture: TTexture, hit: () => void) => {
    const sprite = createSprite({
        tint: SOLID,
        width: Settings.SHIP.size,
        height: Settings.SHIP.size,
        transform: {
            x: Settings.WIDTH / 2,
            y: Settings.HEIGHT / 2
        }
    });
    useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'rect',
            width: Settings.SHIP.size,
            height: Settings.SHIP.size
        },
        gravityScale: 0,
        drag: Settings.SHIP.drag,
        maxSpeed: {
            x: Settings.SHIP.max,
            y: Settings.SHIP.max
        },
        layer: 'ship',
        collidesWith: ['world', 'enemy'],
    });

    const body = getRetroBody2d(useSelf());
    const keys = useKeyboard();
    const pointer = usePointer();
    const timer = useTimer();
    // Shots belong to the scene, so they fly on their own once fired.
    const fire = useSpawn(Shot, { name: 'Shot', parent: 'scene' });
    let ghost = false;

    useUpdate(() => {
        if (body === null) {
            return;
        }
        const across = (keys.isDown('ArrowRight') || keys.isDown('d') ? 1 : 0) - (keys.isDown('ArrowLeft') || keys.isDown('a') ? 1 : 0);
        const down = (keys.isDown('ArrowDown') || keys.isDown('s') ? 1 : 0) - (keys.isDown('ArrowUp') || keys.isDown('w') ? 1 : 0);
        body.acceleration.x = across * Settings.SHIP.push;
        body.acceleration.y = down * Settings.SHIP.push;
    });

    pointer.onDown((info) => {
        const dx = info.worldX - sprite.transform.x;
        const dy = info.worldY - sprite.transform.y;
        const far = Math.hypot(dx, dy) || 1;
        const gap = Settings.SHIP.size;
        fire(sprite.transform.x + dx / far * gap, sprite.transform.y + dy / far * gap, dx / far, dy / far, picture, hit);
    });

    // Hit: for a moment it meets only the walls, and the enemies pass through it.
    body?.onEnter((other) => {
        if (other.name !== 'Enemy' || ghost) {
            return;
        }
        ghost = true;
        sprite.tint = GHOST;
        body.setLayers('ship', ['world']);
        timer.after(1.5, () => {
            ghost = false;
            sprite.tint = SOLID;
            body.setLayers('ship', ['world', 'enemy']);
        });
    });
};
```

`components/shot.ts`:

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

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

export const Shot = (x: number, y: number, dx: number, dy: number, picture: TTexture, hit: () => void) => {
    createSprite({
        texture: picture,
        tint: '#ffd93d',
        width: Settings.SHOT.size,
        height: Settings.SHOT.size,
        transform: {
            x,
            y
        }
    });
    useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'circle',
            radius: Settings.SHOT.size / 2
        },
        gravityScale: 0,
        // A shot meets the walls and the enemies: not the ship, not other shots.
        layer: 'shot',
        collidesWith: ['world', 'enemy'],
    });

    const self = useSelf();
    const body = getRetroBody2d(self);
    body?.setLinearVelocity(dx * Settings.SHOT.speed, dy * Settings.SHOT.speed);
    body?.onEnter((other) => {
        if (other.name === 'Enemy') {
            destroy(other);
            hit();
        }
        destroy(self);
    });
    useTimer().after(Settings.SHOT.life, () => destroy(self));
};
```

`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
        }
    });
};
```

`scenes/demo.ts`:

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

import * as Settings from '../settings';
import { Solid } from '../components/solid';
import { Ship } from '../components/ship';
import { Enemy } from '../components/enemy';
import { paintBall } from '../art/ball';

export const Scene = () => {
    const rng = useRandom();

    // Seen from above: nothing falls.
    useRetroWorld2d({
        gravity: {
            x: 0,
            y: 0
        }
    });

    const wall = useSpawn(Solid, 'Wall');
    wall(Settings.WIDTH / 2, Settings.WALL / 2, Settings.WIDTH, Settings.WALL);
    wall(Settings.WIDTH / 2, Settings.HEIGHT - Settings.WALL / 2, Settings.WIDTH, Settings.WALL);
    wall(Settings.WALL / 2, Settings.HEIGHT / 2, Settings.WALL, Settings.HEIGHT);
    wall(Settings.WIDTH - Settings.WALL / 2, Settings.HEIGHT / 2, Settings.WALL, Settings.HEIGHT);
    // Thin walls in the middle, two pixels: a shot at 600 px/s still stops on them.
    wall(140, 110, 2, 90);
    wall(340, 230, 2, 90);
    wall(240, 70, 90, 2);

    let points = 0;
    const score = createText({
        text: 'SCORE 0',
        transform: {
            x: 60,
            y: 22
        }
    });
    createText({
        text: 'ARROWS OR WASD, CLICK TO SHOOT',
        transform: {
            x: Settings.WIDTH / 2 + 60,
            y: 22
        },
        anchor: {
            x: 0.5,
            y: 0
        }
    });

    const ship = useSpawn(Ship, 'Ship')(paintBall(Settings.SHOT.size), () => {
        points += 10;
        score.text = `SCORE ${points}`;
    });

    // From the corners, now and then.
    const corners = [
        [30, 30], [Settings.WIDTH - 30, 30], [30, Settings.HEIGHT - 30], [Settings.WIDTH - 30, Settings.HEIGHT - 30],
    ];
    const spawnEnemy = useSpawn(Enemy, { name: 'Enemy', parent: 'scene' });
    let alive = 0;
    useTimer().every(Settings.ENEMY.every, () => {
        if (alive >= Settings.ENEMY.most) {
            return;
        }
        const [x, y] = rng.choose(corners);
        alive++;
        spawnEnemy(x, y, ship, () => {
            alive--;
        });
    });

    return createScene();
};
```

`settings.ts`:

```ts
// Seen from above, so the world has no gravity, and everything moves only as it is told:
//
//   the ship is driven by `acceleration`, slowed by `drag` once let go, and held to `maxSpeed`;
//   the shots go at 600 pixels a second and still stop at a wall two pixels thin, because a
//   retro body moves in pieces no longer than the smallest thing it could miss;
//   the layers keep shots from hitting each other or the ship. Two bodies meet only if EACH one
//   meets the other's layer, so the ship leaving 'enemy' out of what it meets is enough;
//   hit, the ship blinks for a moment with `setLayers`, meeting only the walls.

export const WIDTH = 480;
export const HEIGHT = 340;
export const WALL = 8;
export const LAYERS = ['world', 'ship', 'shot', 'enemy'];
export const SHIP = { size: 14, push: 700, drag: 500, max: 170 };
export const SHOT = { size: 5, speed: 600, life: 1.2 };
export const ENEMY = { size: 16, speed: 55, every: 1.1, most: 10 };
```
