npm install @robatbobat/mini-ecs
import { World } from '@robatbobat/mini-ecs';
const world = new World();
const entity = world.addEntity();
or with string id for fast retrival:
const entity = world.addEntity('someId');
Components must implements Component interface:
import { Component } from '@robatbobat/mini-ecs';
export class SomeComponent implements Component {
prop: 'test';
}
entity.addComponent(new SomeComponent());
entity.addComponent(new SomeOtherComponent());
or with chaining:
entity.addComponent(new SomeComponent()).addComponent(new SomeOtherComponent());
Creating query:
To get all entities that have a specific set of components you must pass array of constructors to createQuery method:
const query = world.createQuery([SomeComponent, AnotherComponent]);
Iterate through entities:
query.entities.forEach((enemy) => {
...
});
System example:
import { World, System, Query } from '@robatbobat/mini-ecs';
import { PositionComponent } from '../components/PositionComponent';
import { EnemyComponent } from '../components/EnemyComponent';
export class CollisionSystem implements System {
world: World;
enemies: Query;
constructor(world: World) {
this.world = world;
this.enemies = this.world.createQuery([PositionComponent, EnemyComponent]);
}
update(dt: number) {
this.enemies.entities.forEach((enemy) => {
...
});
}
}
register system in world:
world.registerSystem(new CollisionSystem(world));
loop through registred systems:
world.update();
Entity is not deleted immediately,but marked as removed.
world.removeEntity(entity);
entity will be removed only at the end of world.update()
repo can be found here
Released under the MIT license.