recs
functional entity-component-system experiment
recs allows for the definitions of components, systems, and message handlers on entities in a way that reduces shared state and promotes isolation.
To read more about the ECS pattern, take a look at nano-ecs, the underlying module that powers recs. It's a really useful pattern for writing the core logic in video games.
Usage
var recs = { thispower = 1000} { thisx = 0 thisy = 0 thisxv = 0 thisyv = 0} var Blackhole = Body GravityWellvar Ship = Body recs recs recs recs recsrecsrecs
outputs
blackhole init
ship init
Physics 30 0
Physics 0 0
Suction
Physics 30 0
Physics 1.1111000000740736 0
Suction
Physics 30 0
Physics 3.4204114875106733 0
Suction
You can see a similar graphical demo in action, too.
Core Ideas
Components
Components are any named Javascript functions. For example:
{ thismaxHp = 100 thishp = thismaxHp}
Components define data and not behaviour.
Entities
Entities are a collection of component instances. On their own, they have no
data and no functionality. They are created using recs.entity()
:
recs
Systems
Systems are stateless functions that operate on all entities that have at least the system's required components:
recs
Messages
Messages can be published, in an EventEmitter-style, on a specific entity. Message receivers specify what components they require in order to be received: all applicable receivers are fired.
recs recs recs recs
API
var RECS = var recs = // or var recs =
recs.system([name,] components, func)
Defines a system that runs on all entities that have components
. Runs the
function func
with an entity as its sole parameter.
recs.system([name,] componentsA, componentsB, func)
Defines a system that runs on the cartesian product of all entities that have
componentsA
in one group, and all entities with componentsB
in the other
group. Runs the function func
with signature function (entityA, entityB) {}
.
These systems are particularly useful when two types of entities need to interact regularly, like collision detection:
recs
recs.recv(components, msg, cb)
Registers a message receiver, which fires if a message is sent to an entity that
has the listed components
and the message name msg
. cb
is called with an
entity as its first parameter; any other params passed on send
are included as
subsequent arguments.
recs recs
recs.entity([name,] components[, cb])
Creates a new entity with components components
. cb
is called with a
reference to the brand new entity for any initialization you'd like to do.
recs
recs.tick()
Runs all systems on all applicable entities exactly once. Any arguments passed
into tick()
will be available as additional parameters to all systems called.
This is useful for providing systems with e.g. a time delta.
Install
With npm installed, run
$ npm install recs
Acknowledgments
recs was largely inspired by the regl project.
License
ISC