# Forces and impulses

> A fan with applyForce every frame, a jump pad and a click blast with applyImpulse, on balls of different mass.

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

Three ways to push a retro body besides setting its velocity. `applyForce(x, y)` pushes for this frame only, divided by the body's mass, so it is asked for every frame it should push: the fan, while a ball is in its stream. `applyImpulse(x, y)` is one shove, all at once: the pads, and the blast where you **click**. And `acceleration` keeps pushing until the game changes it, as the platformer shows.

The balls differ in size and so in mass, so the same blast throws the small ones farther.

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

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

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

export const Ball = (x: number, size: number, color: string, picture: TTexture) => {
    const sprite = createSprite({
        texture: picture,
        tint: color,
        width: size,
        height: size,
        transform: {
            x,
            y: 30
        }
    });
    // Heavier the bigger it is.
    const mass = (size / 12) ** 2;
    useRetroBody2d({
        body: 'dynamic',
        collider: {
            shape: 'circle',
            radius: size / 2
        },
        bounce: 0.3,
        mass,
    });

    const body = getRetroBody2d(useSelf());
    if (body === null) {
        return;
    }

    let inFan = false;
    body.onEnter((other) => {
        if (other.name === 'Fan') {
            inFan = true;
        }
        // One kick, the same for every ball: the light ones go higher.
        if (other.name === 'Pad') {
            body.applyImpulse(-120, -Settings.PAD.kick);
        }
    });
    body.onExit((other) => {
        if (other.name === 'Fan') {
            inFan = false;
        }
    });

    useUpdate(() => {
        // A force lasts one frame: asked again every frame it is in the stream. Times the mass,
        // so the fan lifts every ball alike.
        if (inFan) {
            body.applyForce(0, -Settings.FAN.push * mass);
        }
    });

    // The blast: away from where you clicked, weaker farther off.
    usePointer().onDown((info) => {
        const dx = sprite.transform.x - info.worldX;
        const dy = sprite.transform.y - info.worldY;
        const far = Math.max(20, Math.hypot(dx, dy));
        if (far > 160) {
            return;
        }
        const strength = Settings.BLAST * (1 - far / 160) * 2;
        body.applyImpulse(dx / far * strength, dy / far * strength);
    });
};
```

`components/fan.ts`:

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

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

// The fan's stream: a sensor, so balls fly through it. The balls push themselves while inside.
export const Fan = () => {
    const height = Settings.HEIGHT - Settings.WALL - Settings.FAN.top;
    createSprite({
        tint: {
            ...getColor('#5db6ff'),
            a: 0.15
        },
        width: Settings.FAN.w,
        height,
        zIndex: -1,
        transform: {
            x: Settings.FAN.x,
            y: Settings.FAN.top + height / 2
        }
    });
    useRetroBody2d({
        body: 'static',
        sensor: true,
        collider: {
            shape: 'rect',
            width: Settings.FAN.w,
            height
        }
    });
};
```

`components/pad.ts`:

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

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

// A jump pad: solid, and what lands on it is kicked up by the ball's own listener.
export const Pad = () => {
    createSprite({
        tint: '#ff9f45',
        width: Settings.PAD.w,
        height: 8,
        transform: {
            x: Settings.PAD.x,
            y: Settings.HEIGHT - Settings.WALL - 4
        }
    });
    useRetroBody2d({
        body: 'static',
        collider: {
            shape: 'rect',
            width: Settings.PAD.w,
            height: 8
        }
    });
};
```

`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 { Fan } from '../components/fan';
import { Pad } from '../components/pad';
import { Ball } from '../components/ball';
import { paintBall } from '../art/ball';

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

    useRetroWorld2d({
        gravity: {
            x: 0,
            y: 700
        }
    });

    const wall = useSpawn(Solid);
    wall(Settings.WIDTH / 2, Settings.HEIGHT - Settings.WALL / 2, Settings.WIDTH, Settings.WALL);
    wall(Settings.WIDTH / 2, 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);

    useSpawn(Fan, 'Fan')();
    useSpawn(Pad, 'Pad')();

    const picture = paintBall(21);
    const spawnBall = useSpawn(Ball, { name: 'Ball', parent: 'scene' });
    let count = 0;
    const timer = useTimer();
    const dropping = timer.every(0.35, () => {
        spawnBall(rng.rand(40, Settings.WIDTH - 40), rng.randInt(8, 20), rng.choose(Settings.PALETTE), picture);
        count++;
        if (count >= Settings.MOST) {
            dropping.cancel();
        }
    });

    createText({
        text: 'CLICK FOR A BLAST',
        transform: {
            x: Settings.WIDTH / 2,
            y: 30
        },
        anchor: {
            x: 0.5,
            y: 0
        }
    });

    return createScene();
};
```

`settings.ts`:

```ts
// Three ways to push a retro body, besides setting its velocity:
//
//   applyForce(x, y) pushes for THIS frame only, so ask every frame for as long as it should
//   push: the fan, while a ball is in its stream. Divided by the body's mass.
//   applyImpulse(x, y) is one shove, all at once: the pads, and the blast where you click.
//   acceleration keeps pushing until the game changes it (see the platformer).
//
// Ball sizes differ and so do their masses, so the same blast throws the small ones farther.

export const WIDTH = 480;
export const HEIGHT = 340;
export const WALL = 12;
export const FAN = { x: 170, w: 70, top: 60, push: 1500 };
export const PAD = { x: 380, w: 50, kick: 420 };
export const BLAST = 260;
export const MOST = 40;
export const PALETTE = ['#4cff91', '#ff6b6b', '#5db6ff', '#ffd93d', '#c77dff'];
```
