Skip to content

Instantly share code, notes, and snippets.

@Simcamb
Created July 24, 2014 21:06
Show Gist options
  • Save Simcamb/8278e5a2fe781274c18a to your computer and use it in GitHub Desktop.
Save Simcamb/8278e5a2fe781274c18a to your computer and use it in GitHub Desktop.
ig.module('plugins.component')
.requires('impact.entity')
.defines(function () {
/**
* The base class for the components. Provides the needed stubs.
* @type {Component}
*/
Component = ig.Class.extend({
/**
* If you instantiate a component with the "new" keyword, you need to provide
* its owner. A component without an owner is useless.
*
* The preferred way to inject a component to an entity is through the entity's method "addComponent"
* @param owner
* @constructor
*/
init: function (owner) {
this.owner = owner;
},
/**
* This method is automatically called once the entity is instantiated and linked to its owner.
* Use it if you want to perform init code and need a reference to the owner.
*/
added: function () {
},
/**
* Will be called at each Entity's update call
*/
update: function () {
},
/**
* Will be called at each Entity's draw call
*/
draw: function () {
}
});
/**
* Injects Components' management into the Entity Class
*/
ig.Entity.inject({
components: [],
/**
* Each time the entity updates, runs through all of its components
* to update them
*/
update: function () {
this.parent();
if (this.components.length > 0) {
for (var i = 0; i < this.components.length; i++) {
this.components[i].update();
}
}
},
/**
* Instantiates a component and links it to the Entity (the "owner").
* This is the preferred way to inject a component to an entity
* @param comp The instantiated component
* @returns {Component}
*/
addComponent: function (comp) {
comp.owner = this;
comp.added();
this.components.push(comp);
return comp;
},
/**
* Removes a component from its owner.
* @param comp
*/
removeComponent: function (comp) {
for (var i = 0; i < this.components.length; i++) {
if (this.components[i] == comp) {
this.components.splice(i, 1);
}
}
},
/**
* Returns the component(s) of chosen type.
* @param type
* @param {boolean} [firstOnly]
* @returns {Array|Component}
*/
getComponents: function (type, firstOnly) {
firstOnly = typeof firstOnly === 'undefined' ? false : firstOnly;
var components = [];
for (var i = 0; i < this.components.length; i++) {
var component = this.components[i];
if (component.classId === type.classId) {
components.push(component);
if (firstOnly) {
return component;
}
}
}
return components;
},
/**
* A shorthand for getComponents(type, true)
* @param type
* @returns {Component}
* @see getComponents
*/
getCmp: function (type) {
return this.getComponents(type, true);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment