mani-game-engine
TypeScript icon, indicating that this package has built-in type declarations

1.0.0-pre.71 • Public • Published

Use entity component system

import {EntityComponent, GetComponent, GetEntity, Inject, Injector} from 'mani-injector';

class Service {}

class FooComponent {}
class BarComponent {}

class FirstEntity {
    @EntityComponent
    foo: FooComponent = new FooComponent();
}

class SecondEntity {
    @EntityComponent
    foo: FooComponent = new FooComponent();
    @EntityComponent
    bar: BarComponent = new BarComponent();
}

// this system is created for every entity that has a FooComponent
class FooSystem {
    constructor(
        // get a reference to the component when the system is created for a specific entity
        @GetComponent readonly foo: FooComponent,
        // you can get the entity object
        @GetEntity readonly entity:Object 
    ) {}
}

// this system is created for every entity that has a BarComponent
class BarSystem {
    constructor(
        @GetComponent readonly bar: BarComponent,
    ) {}
}

// this system is created for every entity that has a FooComponent and a BarComponent
class FooBarSystem {
    constructor(
        @GetComponent readonly foo: FooComponent,
        @GetComponent readonly bar: BarComponent,
        // you can inject everything that is mapped in the injector
        @Inject readonly service: Service 
    ) {}
}


const injector = new Injector();

injector.registerSystem(FooSystem);
injector.registerSystem(BarSystem);
injector.registerSystem(FooBarSystem);
injector.map(Service).toSingleton();

const entity1 = new FirstEntity();
const entity2 = new SecondEntity();

// array with one instance of FooSystem with a reference to the component
console.log(injector.createSystems(entity1));

// array with 3 systems
// one instance of FooSystem
// one instance of BarSystem
// one instance of FooBarSystem
console.log(injector.createSystems(entity2));

Readme

Keywords

none

Package Sidebar

Install

npm i mani-game-engine

Weekly Downloads

2

Version

1.0.0-pre.71

License

MIT

Unpacked Size

244 kB

Total Files

43

Last publish

Collaborators

  • jmankopf