silphius/app/react-components/entity.jsx
2024-07-04 21:47:14 -05:00

106 lines
2.3 KiB
JavaScript

import {Container, Graphics} from '@pixi/react';
import {memo, useCallback} from 'react';
import {useDebug} from '@/context/debug.js';
import {useMainEntity} from '@/context/main-entity.js';
import Emitter from './emitter.jsx';
import Sprite from './sprite.jsx';
function Aabb({color, width = 0.5, x0, y0, x1, y1, ...rest}) {
const draw = useCallback((g) => {
g.clear();
g.lineStyle(width, color);
g.moveTo(x0, y0);
g.lineTo(x1 + 1, y0);
g.lineTo(x1 + 1, y1 + 1);
g.lineTo(x0, y1 + 1);
g.lineTo(x0, y0);
}, [color, width, x0, x1, y0, y1]);
return (
<Graphics draw={draw} x={0.5} y={0.5} {...rest} />
);
}
function Crosshair({x, y}) {
const draw = useCallback((g) => {
g.clear();
g.lineStyle(1, 0x000000);
g.moveTo(-5, 0);
g.lineTo(5, 0);
g.moveTo(0, -5);
g.lineTo(0, 5);
g.lineStyle(0.5, 0xffffff);
g.moveTo(-5, 0);
g.lineTo(5, 0);
g.moveTo(0, -5);
g.lineTo(0, 5);
g.lineStyle(1, 0x000000);
g.drawCircle(0, 0, 3);
g.lineStyle(0.5, 0xffffff);
g.drawCircle(0, 0, 3);
}, []);
return (
<Graphics draw={draw} x={x} y={y} />
);
}
function Entity({entity, ...rest}) {
const [debug] = useDebug();
const [mainEntity] = useMainEntity();
if (!entity) {
return false;
}
return (
<Container
zIndex={entity.Position?.y || 0}
>
{entity.Sprite && (
<Sprite
entity={entity}
{...rest}
/>
)}
{entity.Emitter && (
<Emitter
entity={entity}
/>
)}
{debug && entity.Position && (
<Crosshair x={entity.Position.x} y={entity.Position.y} />
)}
{debug && (
<Aabb
color={0xff00ff}
{...entity.VisibleAabb}
/>
)}
{debug && entity.Collider && (
<>
<Aabb
color={0xffffff}
width={0.5}
{...entity.Collider.aabb}
/>
{entity.Collider.aabbs.map((aabb, i) => (
<Aabb
color={0xffff00}
width={0.25}
key={i}
{...aabb}
/>
))}
</>
)}
{debug && mainEntity == entity.id && (
<Aabb
color={0x00ff00}
{...entity.Interacts.aabb()}
/>
)}
</Container>
);
}
export default memo(Entity);