# 2D physics

> The 2D physics starting point: boxes rain down and pile up against static walls. In pixels, with y pointing down.

Example `physics-2d`, running at https://nacatamalon.com/en/examples/physics-2d. The whole catalogue: https://nacatamalon.com/llms/examples.md.

Boxes fall, tumble and pile up against static walls. `nacatamalon/physics2d` is an opt-in adapter: a game that never imports it never loads its WebAssembly. The simulation steps at a fixed rate and writes each body back onto its object, in pixels and with y pointing down.

**Click** the canvas to kick the pile. Impulse is mass times speed, and mass is density times area in pixels: that is why the numbers are so large.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';

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

installPhysics2d();

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

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

`components/box.ts`:

```ts
import { createSprite, getColor, usePhysicsBody2d } from 'nacatamalon';

// They are rect colliders because a sprite IS a quad: the collider and the pixels agree
// exactly, so a box visibly rests on its own corner when it topples. A circle is the same
// call with a different shape.
//
// bounce is bounciness (0 dead, 1 perfectly elastic); friction is what eventually stops
// them sliding once they have landed.
export const Box = (x: number, y: number, size: number, rotation: number, tint: string) => {
    createSprite({
        tint: getColor(tint),
        width: size,
        height: size,
        transform: {
            x: x,
            y: y,
            rotation: rotation
        }
    });
    usePhysicsBody2d({
        body: 'dynamic',
        collider: {
            shape: 'rect',
            width: size,
            height: size
        },
        bounce: 0.35,
        friction: 0.5,
        density: 1,
    });
};
```

`components/wall.ts`:

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

// A static object is a wall: infinite mass, never written back, never moved by a contact.
// Each collider is given exactly the picture's own width and height, so what you see is what
// things actually hit.
export const Wall = (x: number, y: number, w: number, h: number) => {
    createSprite({
        tint: '#2a2a3a',
        width: w,
        height: h,
        transform: {
            x: x,
            y: y
        }
    });
    usePhysicsBody2d({
        body: 'static',
        collider: {
            shape: 'rect',
            width: w,
            height: h
        },
        friction: 0.6
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, usePointer, usePhysicsWorld2d, useSpawn } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { getPhysicsBody2d } from 'nacatamalon/physics2d';
import * as Settings from '../settings';
import { Wall } from '../components/wall';
import { Box } from '../components/box';

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

    usePhysicsWorld2d({
        gravity: {
            x: 0,
            y: 900
        }
    });

    useSpawn(Wall)(Settings.WIDTH / 2, Settings.HEIGHT - Settings.WALL / 2, Settings.WIDTH, Settings.WALL);
    useSpawn(Wall)(Settings.WALL / 2, Settings.HEIGHT / 2, Settings.WALL, Settings.HEIGHT);
    useSpawn(Wall)(Settings.WIDTH - Settings.WALL / 2, Settings.HEIGHT / 2, Settings.WALL, Settings.HEIGHT);

    // A rain of boxes dropped from above the top edge. Each one is its own object, because a
    // collider belongs to an object the way its picture does: one object, one collider.
    const spawnBox = useSpawn(Box);
    const boxes: ReturnType<typeof spawnBox>[] = [];

    for (let i = 0;i < 10;i++) {
        const size = rng.rand(18, 30);

        boxes.push(spawnBox(
            rng.rand(Settings.WALL + 10 + size / 2, Settings.WIDTH - Settings.WALL - 40),
            -size / 2 - i * 45,
            size,
            rng.rand(-0.6, 0.6),
            rng.choose(Settings.PALETTE),
        ));
    }

    // Click the canvas to kick the pile. The engine hands back what an object is MADE OF, so the
    // shove goes to the body the simulation made of it, asked for when needed.
    //
    // Impulse is mass times speed, and mass here is density times area in PIXELS, so a 24px
    // box weighs about 576 and the numbers are large to match the unit, not because they are
    // magic.
    const pointer = usePointer();

    pointer.onDown(() => {
        for (const box of boxes) {
            getPhysicsBody2d(box)?.applyImpulse(rng.rand(-40000, 40000), -90000);
        }
    });

    return createScene();
};
```

`settings.ts`:

```ts
// Two conventions to keep straight, both inherited from flat scenes rather than invented by
// the adapter:
//
//   1. Units are PIXELS, because the writeback is direct, so gravity is px/s2 and not m/s2.
//   2. +y is DOWN. A flat placement's y grows downward, so gravity is POSITIVE. That is the
//      opposite sign from three dimensions, where up is +y.
//
// And one that is this engine's rather than physics': an object's placement is the MIDDLE of
// what it places, which is also where the simulation positions a body, so the two already agree and
// there is no offset to work out. (The other engine places a picture by its top-left corner,
// and its adapter has to bridge the two.)

export const WIDTH = 480;
export const HEIGHT = 320;
export const WALL = 16;
export const PALETTE = ['#4cff91', '#ff6b6b', '#5db6ff', '#ffd93d', '#c77dff', '#ff9f45'];
```
