Giter Club home page Giter Club logo

ces.js's Introduction

CES.js

CES.js is a lightweight Component-Entity-System framework for JavaScript games.

Basic Usage

To define a new component, simply extend CES.Component. Note that each component should have a unique name property.

var Position = CES.Component.extend({
    name: 'position',
    init: function (x, y) {
        this.x = x;
        this.y = y;
    }
});

var Velocity = CES.Component.extend({
    name: 'velocity',
    init: function (x, y) {
        this.x = x;
        this.y = y;
    }
});

var Health = CES.Component.extend({
    name: 'health',
    init: function (maxHealth) {
        this.health = this.maxHealth = maxHealth;
    },
    isDead: function () {
        return this.health <= 0;
    },
    receiveDamage: function (damage) {
        this.health -= damage;
    }
});

An entity is essentially a container of one or more components.

var hero = new CES.Entity();
hero.addComponent(new Position(0, 0));
hero.addComponent(new Velocity(0, 0));
hero.addComponent(new Health(100));

The system is responsible for updating the entities. In a real game there may be a lot of systems, like CollisionSystem, RenderSystem, ControlSystem etc.

var PhysicSystem = CES.System.extend({
    update: function (dt) {
        var entities, position, velocity;

        entities = this.world.getEntities('position', 'velocity');

        entities.forEach(function (entity) {
            position = entity.getComponent('position');
            velocity = entity.getComponent('velocity');
            position.x += velocity.x * dt;
            position.y += velocity.y * dt;
        });
    }
});

The world is the container of all the entities and systems. Calling the update method will sequentially update all the systems, in the order they were added.

var world = new CES.World();

world.addEntity(hero);
// ... add other entities

world.addSystem(new PhysicSystem());
// ... add other systems

requestAnimationFrame(function () {
    world.update(/* interval */);
})

A system is notified when it is added or removed from the world:

var MySystem = CES.System.extend({
  addedToWorld: function(world)  {
    // Code to handle being added to world. Remeber to call this._super.
    this._super(world);
  },
  removedFromWorld: function(world) {
    // Code to handle being removed from world.
    this._super(world);
  }
});

The world emits signals when entities are added or removed. You can listen for specific entities and handle the signal accordingly:

var MySystem = CES.System.extend({
  addedToWorld: function(world) {
    world.entityAdded('position', 'velocity').add(function(entity) {
      // This function is called whenever an entity with both 'position' and
      // 'velocity' components is added to the world. It can also be called when
      // a component is added to an entity; for example, when an entity with
      // only 'position' has 'velocity' added to it.
    });
    world.entityRemoved('position', 'velocity').add(function(entity) {
      // This function is called whenever an entity with both 'position' and
      // 'velocity' components is removed from the world. It can also be called 
      // when a component is removed from an entity; for example, when an entity
      // with both 'position' and 'velocity' has 'velocity' removed from it.
    });
  }
});

Installation (Browser)

Download the minified js file and include it in your web page.

<script type="text/javascript" src="./ces-browser.min.js"></script>

Installation (Node.js)

If you want to use it in Node.js, you may install it via npm.

npm install ces

Then, in your program:

var CES = require('ces');

Development

Layout:

.
|-- dist         # browser distribution
|-- src          # source code
`-- test         # test scripts

You will need to install node.js and use npm to install the dependencies:

npm install -d 

To build the browser distribution (It will use node-browserify to generate a browser distribution, and use UglifyJS to compress):

make

To run the tests with mocha and should.js

make test

License

MIT License

Copyright 2013 Xueqiao Xu <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

ces.js's People

Contributors

qiao avatar alexdmiller avatar mflux avatar

Stargazers

 avatar  avatar Zed Hanok avatar Ronja Schnur avatar  avatar baibukan avatar  avatar .ss avatar  avatar catsout avatar wangRan avatar  avatar  avatar Jeferson Belmiro avatar Vis avatar Garrett Guillotte avatar pepebe avatar LeftStyle avatar  avatar  avatar Syntax avatar  avatar Mikk Pristavka avatar  avatar  avatar 45deg avatar uynet avatar Championrunner avatar Kenneth Bruskiewicz avatar Prima Kurnia avatar Arsyel avatar  avatar Soma Szelpal avatar  avatar Yu avatar  avatar ihaiu avatar Gustavo Giserman avatar Danilo Bezerra avatar Geoffroy Lafontaine avatar Leo Dutra avatar Yacine Rezgui avatar Saman Bemel-Benrud avatar  avatar Philippe Cochin avatar April Taylor avatar Faded Weiss avatar Nikita Zhenev avatar 蝉闹外 avatar Lee Nan Ho avatar Alexandre Baticle avatar  avatar km avatar Sven-Eric Matthes avatar Rafael C.P. avatar Nathan avatar Dee Cheung avatar abner avatar Andy Cao avatar Dmitrii Vasilev avatar  avatar monkeytao avatar wang.hanbin avatar Jimmy Breck-McKye avatar hugo avatar  avatar James Go avatar Lingjia Liu avatar Sean Brown avatar pjstein avatar Jonathan Q. avatar Alejandro Jiménez Encinas avatar Josiah Savary avatar Thais Robba avatar Rob Voss avatar  avatar Osman Zeki avatar Jeff Swenson avatar Jack Wilsdon avatar James B. Pollack, MFA  avatar  avatar Hitoshi Tsuyuki avatar Simon Oberhammer avatar Boris Berak avatar Russell Chapman avatar  avatar Ignacio Muñoz Fernández avatar Szymon Kaliski avatar Scott Goetz avatar Karthik VJ avatar CZQ avatar Diego Ferri avatar Darach Ennis avatar Aspirin Shi avatar Matt Zhang avatar Joe Illuminati avatar Alex Psi avatar Calvin Sauer avatar Ben McEldowney avatar TinkGu avatar

Watchers

Bruce Onder avatar  avatar James Cloos avatar Michael Anthony avatar Jhonson Ozuna Mejia avatar  avatar Donald Baird avatar jesonXie avatar  avatar Dylan Dion avatar

ces.js's Issues

`entityAdded` order issue

CES = require('ces')
CompA = CES.Component.extend({name: 'a'})
CompB = CES.Component.extend({name: 'b'})
var world = new CES.World();

world.entityAdded('b').add(function (entity) {
    console.log('b')
});

world.entityAdded('a').add(function (entity) {
    console.log('a')
    entity.addComponent(new CompB());
});


var entity = new CES.Entity();
entity.addComponent(new CompA());
world.addEntity(entity);

result

a

Change entityAdded order.

CES = require('ces')
CompA = CES.Component.extend({name: 'a'})
CompB = CES.Component.extend({name: 'b'})
var world = new CES.World();


world.entityAdded('a').add(function (entity) {
    console.log('a')
    entity.addComponent(new CompB());
});

world.entityAdded('b').add(function (entity) {
    console.log('b')
});



var entity = new CES.Entity();
entity.addComponent(new CompA());
world.addEntity(entity);

result

a
b

Dist / zip is out of date

Hi Qiao, really eager to start working with this lib, looks to be well thought out and designed.

I've noticed the dist and zip are both out of date and the examples do not work because of this. For example, addedToWorld does not actually get called in the dist version. I noticed these discrepancies when trying the example, so I had to pull the repo, delete dist, then npm install -d, then make, then copied over the new build.

V8 optimization

Is CES.js optimized for the v8 javascript engine? I noticed you were using John Resig's inheritance class for extending your objects, but in my own projects I've found that really bogs down the code optimization. I'm actually moving to using an entity component system to get away from using inheritance chains, but I see you're using them in your engine. Do you have any performance measures that you could show me?Just to ensure that If I go with CES, I won't be adding just another inheritance layer on top of my already existing one. Thanks!

MMORPG

can I use this for an MMORPG server? How can I dynamically create an entity? Like there will be a lot of entities and data will be different for each of them.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.