I made an Entity Component System for React. You implement Entity-components as React-components:
class Position extends Facet<Position> {
location? = new Vector2(0, 0);
}
class Velocity extends Facet<Velocity> {
amount? = new Vector2(0, 0);
}
Systems are defined as functions that utilize queries to find the entities with the components they need:
const PhysicsSystem = () => {
const query = useQuery((e) => e.hasAll(Position, Velocity));
return useSystem((dt) => {
query.loop([Position, Velocity], (e, [pos, vel]) => {
pos.location = pos.location.clone().add(vel.amount);
});
});
};
You can then tie it all together in a React component representing your simulation:
export const Particles = () => {
const ECS = useECS();
useAnimationFrame(ECS.update);
return (
<ECS.Provider>
<LifetimeSystem />
<PhysicsSystem />
<GravitySystem vector={new Vector2(0, 10)} />
<Emitter emissionDelay={0.025}>
{() => {
const pos = randomVector(50).add(new Vector2(250, 100));
return (
<Entity>
<Lifetime timeleft={3} />
<Position location={pos} />
<Velocity amount={randomVector(10)} />
</Entity>
);
}}
</Emitter>
</ECS.Provider>
)
}