@robatbobat/mini-ecs

lightweight ECS library

Usage no npm install needed!

<script type="module">
  import robatbobatMiniEcs from 'https://cdn.skypack.dev/@robatbobat/mini-ecs';
</script>

README

Build Status Coverage Status NPM NPM MIT License

lightweight ECS library

Installation

npm install @robatbobat/mini-ecs

Usage

import { World } from '@robatbobat/mini-ecs';

const world = new World();

Creating Entity

const entity = world.addEntity();

or with string id for fast retrival:

const entity = world.addEntity('someId');

Components

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());

System and Querying

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();

Remove Entity

Entity is not deleted immediately,but marked as removed.

world.removeEntity(entity);

entity will be removed only at the end of world.update()

Example project:

live demo

repo can be found here


License

Released under the MIT license.