Game Development Reference
In-Depth Information
the
worldPosition
property to calculate the actual position of the sprite on the screen. Here is a
simplified version of the
SpriteGameObject
class:
function SpriteGameObject(sprite, layer) {
GameObject.call(this, layer);
this.sprite = sprite;
this.origin = Vector2.zero;
}
SpriteGameObject.prototype = Object.create(GameObject.prototype);
SpriteGameObject.prototype.draw = function () {
if (!this.visible)
return;
Canvas2D.drawImage(this.sprite, this.worldPosition, 0, 1, this.origin);
};
Have a look at the complete version of the class in the
JewelJam3
example code. That version adds
a few useful properties such as a property for retrieving the width of the sprite game object.
A List of Game Objects
The next type of game object consists of a list of other game objects. This is a very useful type,
because it allows you to create hierarchical structures of game objects. For example, the
root
game object needs to be a list of other game objects, because it contains the background sprite
game object as well as the playing field. To represent a game object containing a list of other game
objects, you use a class called
GameObjectList
. This class inherits from the
GameObject
class, so a
list of game objects is, itself, also a game object. This way, you can treat it as a normal game object
and give it a position, a velocity, a drawing layer, or a parent game object. Furthermore, a game
object in the list can itself be a list of other game objects. This design of the
GameObjectList
class
allows you to define hierarchical structures of game objects. To manage a list of game objects, you
need to add an array member variable that contains the (child) game objects. Here is the complete
constructor of
GameObjectList
:
function GameObjectList(layer) {
GameObject.call(this, layer);
this._gameObjects = [];
}
One of the goals of the
GameObjectList
class is to take care of the game objects in its list. This
means, if you call the
draw
method of a
GameObjectList
instance, this instance draws all the game
objects that are in its list. The same procedure needs to be followed if the
handleInput
method is
called or if the
update
method is called. Here is the
update
method defined in
GameObjectList
:
GameObjectList.prototype.update = function (delta) {
for (var i = 0, l = this._gameObjects.length; i < l; ++i)
this._gameObjects[i].update(delta);
};
Search WWH ::
Custom Search