silphius/app/react-components/water.jsx
2024-07-07 17:34:40 -05:00

52 lines
1.3 KiB
JavaScript

import {Container, Graphics} from '@pixi/react';
import {forwardRef, useCallback, useEffect, useRef, useState} from 'react';
const WaterTile = forwardRef(function WaterTile({height, width}, ref) {
const draw = useCallback((g) => {
g.clear();
g.beginFill(0x000000);
g.drawRect(
0,
0,
width,
height
);
}, [height, width]);
return <Graphics alpha={0} draw={draw} ref={ref} />
});
export default function Water({mask, tileLayer, water}) {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
const waterTile = useRef();
const waterTiles = [];
if (mounted) {
for (const tileIndex in water) {
const tileIndexNumber = parseInt(tileIndex);
const tx = tileIndexNumber % tileLayer.area.x;
const ty = (tileIndexNumber - tx) / tileLayer.area.x;
waterTiles.push(
<Graphics
x={tx * tileLayer.tileSize.x}
y={ty * tileLayer.tileSize.y}
alpha={Math.floor(water[tileIndex]) / (256 * 2)}
key={tileIndex}
geometry={waterTile.current}
/>
);
}
}
return (
<Container mask={mask}>
<WaterTile
height={tileLayer.tileSize.y}
ref={waterTile}
width={tileLayer.tileSize.x}
/>
{waterTiles}
</Container>
);
}