0.0.3 • Published 8 years ago

@turtlemay/ecs v0.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
8 years ago

Installation

npm install @turtlemay/ecs

Basic Usage

Create Entitys:

import {Entity} from '@turtlemay/ecs';

const entity = new Entity();

Define your components by extending the Component base class:

import {Component} from '@turtlemay/ecs';

class MyComponent extends Component {}

Add and remove components:

entity.addComponent(MyComponent);
entity.removeComponent(MyComponent);
entity.clearComponents();

Get attached components:

const c = entity.getComponent(MyComponent);

Enable and disable components:

c.enabled = true; // false

Use callbacks to implement your component logic. Available callbacks: onAttach, onDetach, onEnable, onDisable, onUpdate, onPostUpdate

class MyComponent extends Component {
  onAttach() {
  	console.log(`Component attached to an entity.`);
  }
}

Access the host entity from a component:

class MyComponent extends Component {
  onAttach() {
  	console.log(this.entity);
  }
}

Components are enabled by default. Start your component in a disabled state:

class MyComponent extends Component {
  constructor() {
    super();
    this.startEnabled = false; // Default true
  }
}

Update all attached components on an entity:

import {updateEntity} from '@turtlemay/ecs';

updateEntity(entity);

Additional Usage

The library does not concern itself with how you manage your entities or when you choose to update them.

Example of representing your arbitrary objects as entities:

/** Weakmap our objects to entity instances. */
const wmap = new WeakMap();

/** Create/cache an entity instance for an arbitrary object. */
function entity(object) {
  if (!wmap.has(object)) wmap.set(object, new Entity());
  return wmap.get(object);
}

// Use your arbitrary object like an entity:
const myObj = {};
entity(myObj).addComponent(MyComponent);

/* (Once you clear all attached components and dereference your object, the corresponding entity can also be garbage-collected.) */

Update a collection of entities:

const entities = new Set();
for (const entity of entities) {
  updateEntity(entity);
}

The library does not keep its own delta time. Since you are free to update your entities at any time you should access delta time through your engine implementation or calculate it during whichever update loop you're using.