# Space rocks

> Wrapping at the edges, one top speed whichever way, a picture that turns over a square collider, and shots fired by angle.

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

Space, the old way: nothing falls, and what leaves by one edge comes back by the other (`bounds: 'wrap'`, the world's edges being the screen when it gives none). `onBounds` says when.

The ship turns its picture with `angularVelocity` (a retro collider never turns, its square stays square), thrusts with `acceleration` the way it faces, and is held to one top speed whichever way it goes (`maxSpeed: 170`). Shots leave the way it faces with `setVelocityFromAngle`. Rocks pass through each other, because their layer does not meet itself. **Left** and **right** to turn, **up** to thrust, **Space** or **Z** to fire.

## 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: '#05050c',
    physicsLayers: Settings.LAYERS,
});

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

`components/rock.ts`:

```ts
import { createShapes, destroy, useRetroBody2d, useSelf, useTransform } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { getRetroBody2d } from 'nacatamalon/retro-physics2d';

// A rock: a lumpy outline that spins as it drifts, a circle to collide with. Shot, it breaks in two
// smaller ones until it is small enough to vanish.
export const Rock = (x: number, y: number, radius: number, split: (x: number, y: number, radius: number) => void) => {
    const rng = useRandom();
    useTransform({
        x,
        y
    });
    const corners = 9;
    createShapes({
        shapes: [{
            type: 'polygon',
            points: Array.from({ length: corners }, (_, i) => {
                const angle = (i / corners) * Math.PI * 2;
                const far = radius * rng.rand(0.75, 1.1);
                return { x: Math.cos(angle) * far, y: Math.sin(angle) * far };
            }),
            stroke: { width: 1, color: '#9badb7' },
        }]
    });
    useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'circle',
            radius
        },
        gravityScale: 0,
        bounds: 'wrap',
        layer: 'rock',
        // Rocks meet the ship and the shots, not each other.
        collidesWith: ['ship', 'shot'],
        mass: radius,
    });

    const self = useSelf();
    const body = getRetroBody2d(self);
    if (body === null) {
        return;
    }
    body.setVelocityFromAngle(rng.rand(0, Math.PI * 2), rng.rand(20, 60) * (20 / radius));
    body.angularVelocity = rng.rand(-1.5, 1.5);

    body.onEnter((other) => {
        if (other.name !== 'Shot') {
            return;
        }
        destroy(other);
        destroy(self);
        if (radius > 6) {
            const at = self.transform!;
            split(at.x, at.y, radius / 2);
            split(at.x, at.y, radius / 2);
        }
    });
};
```

`components/ship.ts`:

```ts
import { createShapes, useKeyboard, useRetroBody2d, useSelf, useSpawn, useTransform, useUpdate } from 'nacatamalon';
import { getRetroBody2d } from 'nacatamalon/retro-physics2d';

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

export const Ship = () => {
    const place = useTransform({
        x: Settings.WIDTH / 2,
        y: Settings.HEIGHT / 2
    });
    // Drawn pointing right: it turns with its object.
    createShapes({
        shapes: [
            { type: 'polygon', points: [{ x: 8, y: 0 }, { x: -6, y: -5 }, { x: -3, y: 0 }, { x: -6, y: 5 }], stroke: { width: 1, color: '#e8e8f0' } },
        ]
    });
    useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'rect',
            width: 10,
            height: 10
        },
        gravityScale: 0,
        maxSpeed: Settings.SHIP.max,
        drag: Settings.SHIP.drag,
        bounds: 'wrap',
        layer: 'ship',
        collidesWith: ['rock'],
    });

    const self = useSelf();
    const body = getRetroBody2d(self);
    const keys = useKeyboard();
    const fire = useSpawn(Shot, { name: 'Shot', parent: 'scene' });

    body?.onEnter((other) => {
        // Hit: back to the middle, still.
        if (other.name === 'Rock') {
            place.x = Settings.WIDTH / 2;
            place.y = Settings.HEIGHT / 2;
            body.setLinearVelocity(0, 0);
        }
    });

    useUpdate(() => {
        if (body === null) {
            return;
        }
        body.angularVelocity = ((keys.isDown('ArrowRight') ? 1 : 0) - (keys.isDown('ArrowLeft') ? 1 : 0)) * Settings.SHIP.turn;
        const thrust = keys.isDown('ArrowUp') ? Settings.SHIP.thrust : 0;
        body.acceleration.x = Math.cos(place.rotation) * thrust;
        body.acceleration.y = Math.sin(place.rotation) * thrust;
        if (keys.justPressed(' ') || keys.justPressed('z')) {
            fire(place.x + Math.cos(place.rotation) * 9, place.y + Math.sin(place.rotation) * 9, place.rotation);
        }
    });
};
```

`components/shot.ts`:

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

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

export const Shot = (x: number, y: number, angle: number) => {
    useTransform({
        x,
        y
    });
    createShapes({
        shapes: [{ type: 'circle', x: 0, y: 0, radius: 1.5, fill: '#ffd93d' }]
    });
    useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'circle',
            radius: 1.5
        },
        gravityScale: 0,
        bounds: 'wrap',
        layer: 'shot',
        collidesWith: ['rock'],
    });
    const self = useSelf();
    getRetroBody2d(self)?.setVelocityFromAngle(angle, Settings.SHOT.speed);
    useTimer().after(Settings.SHOT.life, () => destroy(self));
};
```

`scenes/demo.ts`:

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

import * as Settings from '../settings';
import { Ship } from '../components/ship';
import { Rock } from '../components/rock';

export const Scene = () => {
    const rng = useRandom();
    // No gravity, and no edges given: the screen's.
    useRetroWorld2d({
        gravity: {
            x: 0,
            y: 0
        }
    });

    const spawnRock = useSpawn(Rock, { name: 'Rock', parent: 'scene' });
    const split = (x: number, y: number, radius: number) => spawnRock(x, y, radius, split);
    for (let i = 0; i < Settings.ROCKS; i++) {
        // Round the edges, away from the ship.
        const angle = (i / Settings.ROCKS) * Math.PI * 2;
        split(Settings.WIDTH / 2 + Math.cos(angle) * 140, Settings.HEIGHT / 2 + Math.sin(angle) * 120, rng.rand(14, 20));
    }
    useSpawn(Ship, 'Ship')();

    createText({
        text: 'LEFT RIGHT TO TURN, UP TO THRUST, SPACE TO FIRE',
        transform: {
            x: Settings.WIDTH / 2,
            y: 16
        },
        anchor: {
            x: 0.5,
            y: 0
        }
    });

    return createScene();
};
```

`settings.ts`:

```ts
// Space, the old way: nothing falls, and what leaves by one edge comes back by the other
// (`bounds: 'wrap'`, the world's edges being the screen when it gives none). `onBounds` says when.
//
// The ship turns its picture with `angularVelocity` (a retro collider never turns, its square stays
// square), thrusts with `acceleration` the way it faces, and is held to one top speed whichever way
// it goes (`maxSpeed: 170`). Shots leave the way it faces with `setVelocityFromAngle`. Rocks pass
// through each other: their layer does not meet itself.

export const WIDTH = 480;
export const HEIGHT = 320;
export const LAYERS = ['ship', 'shot', 'rock'];
export const SHIP = { turn: 4, thrust: 260, max: 170, drag: 40 };
export const SHOT = { speed: 320, life: 0.9 };
export const ROCKS = 5;
```
