Game Development Reference
In-Depth Information
Because you can use a regular array to represent two-dimensional structures, the GameObjectGrid
class is a subclass of GameObjectList . You need to do a few additional things to make the
GameObjectGrid class behave the way you want it to. First, you need to be able to calculate anchor
positions, which means you need to know the size of a single element ( cell ) in the grid. Therefore,
you also add two member variables to store the size of a single cell in the grid. In addition, you store
the number of desired rows and columns in a member variable. These values have to be passed
to the constructor as a parameter when a GameObjectGrid instance is created. This is the complete
constructor method:
function GameObjectGrid(rows, columns, layer) {
GameObjectList.call(this, layer);
this.cellWidth = 0;
this.cellHeight = 0;
this._rows = rows;
this._columns = columns;
}
GameObjectGrid.prototype = Object.create(GameObjectList.prototype);
Also, add two properties to the class so you can read the number of rows and columns:
Object.defineProperty(GameObjectGrid.prototype, "rows", {
get: function () {
return this._rows;
}
});
Object.defineProperty(GameObjectGrid.prototype, "columns", {
get: function () {
return this._columns;
}
});
Because you inherited from GameObjectList , you already have a method for adding a game object.
However, you need to do things slightly differently in this class. Because the game objects are
placed in a (flat) grid, the drawing order isn't really important anymore. When you add a game object,
you don't want to sort the array. Furthermore, you want to set the position of the game object to its
desired position in the grid. To do this, you override the add method from GameObjectList as follows:
GameObjectGrid.prototype.add = function (gameobject) {
var row = Math.floor(this._gameObjects.length / this._columns);
var col = this._gameObjects.length % this._columns;
this._gameObjects.push(gameobject);
gameobject.parent = this;
gameobject.position = new Vector2(col * this.cellWidth, row * this.cellHeight);
};
 
Search WWH ::




Custom Search