# Formation

> Forty sprites sharing one texture, placed and animated as one group.

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

A 10×4 grid of sprites sharing one texture, each offset on a wave by its place in the grid, so the block ripples like an arcade enemy formation.

One object owns the whole grid and one `useUpdate` drives every unit. And since they share a texture, the engine draws them in one go.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { WIDTH, HEIGHT } from './settings';

import { Formation } from './scenes/demo';

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

// Declare Scenes
game({
    Formation
});
```

`components/fleet.ts`:

```ts
import type { TSprite } from 'nacatamalon';
import { createSprite, useLoadTexture, useUpdate } from 'nacatamalon';
import * as Settings from '../settings';

export const Fleet = () => {
    const texture = useLoadTexture({
        src: '/example-assets/assets/gammix.png',
        key: 'unit'
    });

    // One texture for all forty, so the renderer draws them as a single batch.
    const units: { sprite: TSprite; baseX: number; baseY: number; phase: number }[] = [];

    for (let row = 0; row < Settings.ROWS; row++) {
        for (let col = 0; col < Settings.COLS; col++) {
            const baseX = 84 + col * 36;
            const baseY = 84 + row * 42;

            const sprite = createSprite({
                texture,
                width: 24,
                height: 24,
                transform: {
                    x: baseX,
                    y: baseY,
                    rotation: 0,
                    scaleX: 1,
                    scaleY: 1
                },
            });

            units.push({
                sprite,
                baseX,
                baseY,
                phase: (col + row) * 0.4
            });
        }
    }

    useUpdate((_delta, time) => {
        for (const unit of units) {
            unit.sprite.transform.x = unit.baseX + Math.sin(time * Settings.SPEED + unit.phase) * 18;
            unit.sprite.transform.y = unit.baseY + Math.cos(time * Settings.SPEED + unit.phase) * 8;
        }
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useSpawn } from 'nacatamalon';

import { Fleet } from '../components/fleet';

export const Formation = () => {
    useSpawn(Fleet)();

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
export const COLS = 10;
export const ROWS = 4;
export const SPEED = 2;
```
