# Parallax

> Five forest layers, each at its own speed: the 16-bit depth illusion.

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

Five forest layers, each an object of its own with its own speed. Each layer is one full-screen image drawn twice, side by side: when a copy slides fully off to the left it jumps two widths to the right, so the loop has no seam.

Slower reads as farther away: the depth trick every 16-bit platformer leaned on.

## Code

`index.ts`:

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

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

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

`components/layer.ts`:

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

export const Layer = ({ src, speed }: { src: string; speed: number }) => {
    const texture = useLoadTexture({
        src
    });

    const copies: TSprite[] = [];

    for (let i = 0; i < 2; i++) {
        copies.push(createSprite({
            texture,
            width: Settings.WIDTH,
            height: Settings.HEIGHT,
            // By its corner: the default is the middle, which is what something standing
            // somewhere wants and not what a full-screen layer does.
            anchor: {
                x: 0,
                y: 0
            },
            transform: {
                x: i * Settings.WIDTH,
                y: 0,
                rotation: 0,
                scaleX: 1,
                scaleY: 1
            },
        }));
    }

    useUpdate((dt) => {
        for (const c of copies) {
            c.transform.x -= speed * dt;

            if (c.transform.x <= -Settings.WIDTH) {
                c.transform.x += 2 * Settings.WIDTH;
            }
        }
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useSpawn } from 'nacatamalon';
import * as Settings from '../settings';
import { Layer } from '../components/layer';

export const Parallax = () => {
    const layer = useSpawn(Layer);

    for (const [src, speed] of Settings.LAYERS) {
        layer({
            src,
            speed
        });
    }

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;

export const LAYERS = [['/example-assets/assets/complete_maps/forest/background/Layers/1.png', 8], ['/example-assets/assets/complete_maps/forest/background/Layers/2.png', 18], ['/example-assets/assets/complete_maps/forest/background/Layers/3.png', 34], ['/example-assets/assets/complete_maps/forest/background/Layers/4.png', 60], ['/example-assets/assets/complete_maps/forest/background/Layers/5.png', 95],] satisfies [string, number][];
```
