Created
April 9, 2015 00:08
-
-
Save naps62/a9241a43bc93d8bec164 to your computer and use it in GitHub Desktop.
A JS component pattern implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var GameObject = function(name) { | |
this.name = name || "gameObject"; | |
this.components = []; | |
} | |
GameObject.prototype.update = function() { | |
this.components.map(function(component) { | |
if (!!component.update) { | |
component.update(); | |
} | |
}); | |
} | |
GameObject.prototype.render = function() { | |
this.components.map(function(component) { | |
if (!!component.render) { | |
component.render(); | |
} | |
}); | |
} | |
GameObject.prototype.getComponents = function(type) { | |
return this.components.filter(function(component) { | |
return type == null || (component instanceof type); | |
}); | |
} | |
GameObject.prototype.getComponent = function(type) { | |
return this.getComponents(type)[0]; | |
} | |
GameObject.prototype.addComponent = function(type, options) { | |
var component = new type(this, options); | |
this.components.push(component); | |
} | |
var Transform = function(owner, options) { | |
this.owner = owner; | |
this.x = options.x || 0; | |
this.y = options.y || 0; | |
} | |
Transform.prototype.render = function() { | |
console.log(this.owner.name + ': ('+ this.x + ', ' + this.y +')') | |
} | |
var LinearMovement = function(owner, options) { | |
this.owner = owner; | |
this.offX = options.offX || 0; | |
this.offY = options.offY || 0; | |
} | |
LinearMovement.prototype.update = function() { | |
var transform = this.owner.getComponent(Transform); | |
transform.x += this.offX; | |
transform.y += this.offY; | |
} | |
var rectToRight = new GameObject("rectToRight"); | |
rectToRight.addComponent(Transform, { | |
x: 10, | |
y: 20 | |
}); | |
rectToRight.addComponent(LinearMovement, { | |
offX: 10, | |
offY: 0 | |
}); | |
var rectToBottom = new GameObject("rectToBottom"); | |
rectToBottom.addComponent(Transform, { | |
x: 10, | |
y: 20 | |
}); | |
rectToBottom.addComponent(LinearMovement, { | |
offX: 0, | |
offY: 10 | |
}); | |
var scene = [rectToRight]; | |
var update = function() { | |
scene.map(function(object) { | |
object.update(); | |
}); | |
} | |
var render = function() { | |
scene.map(function(object) { | |
object.render(); | |
}); | |
} | |
setInterval(update, 500); | |
setInterval(render, 1300); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment