@axc/ecs-ts

ecs-ts is 60 loc library that provides utilities to build entity component systems

Usage no npm install needed!

<script type="module">
  import axcEcsTs from 'https://cdn.skypack.dev/@axc/ecs-ts';
</script>

README

About

ecs-ts is 60 loc library that provides utilities to build entity component systems

Getting Started

Install the package via npm

npm install @axc/ecs-ts

A simple demo

import {World} from '@axc/ecs-ts';

const world = new World();

const yourEntity = {
    id: '1',
    foo: 'World!'
}
world.entities.push(yourEntity);

world.registerSystem((entities, event,world)=>{
    for(let entity in entities){
        if(entity.foo){
            console.log('Hello' + entity.foo);
        }
    }
},'periodic', 1);

world.dispatch({type: 'periodic',dt: 1000/60});

Documentation

Entity

An entity is a dictionary that holds an id and component data

const entity = {
    id: '1',
    body: createBodyComponent(),
    health: createHealthComponent()
}

System

A system is a function that performs some operations on the entities when the event it listens to is dispatched.

const system = (entities, event, world)=>{
    for(let entity in entities){
        //do some work
    }
}

Common System operations can be abstarcted via Higher Order Functions, for example, a common use case is to only iterate on entites that have a set of components, that can be achieved by the utility function provided by this library This can be implemented easily as follows

const regularSystem = (system, components)=>{
    return(entities, event, world)=>{
        system(
            enties.filter(entity =>components.every((component) => !!(Object.keys(entity)).find((key)=>key === component))),
            event,
            world
        )
    }
}
const physicsSystem = regularSystem((entities, event, world)=>{
    for(let entity in entities){
        //entity will allways contain body component
        phsyicsEngine.update(entity);
    }
}, ['body']);

World

The world holds all the data required for a simulation to run, that is, the entities and the systems. On top of that, its api allows you to dispatch events that are listened by your systems.

import {World} from '@axc/ecs-ts';

const world = new World();

world.registerSystem(yourSystem,'periodic');

world.dispatch({type: 'periodic' dt: 1000/60});

API Documentation

You can see the automatically generated documentation here