Game Development Reference
In-Depth Information
As you can see in this example, you calculate the row and column indices from the target location in
the array. Then you push the game object on the array, set its parent, and, using the calculated row
and column indices, determine its position. For convenience, add another method that allows you to
add a game object at a specific row and column index in the grid:
GameObjectGrid.prototype.addAt = function (gameobject, col, row) {
this._gameObjects[row * this._columns + col] = gameobject;
gameobject.parent = this;
gameobject.position = new Vector2(col * this.cellWidth, row * this.cellHeight);
};
A Grid of Jewels
For the Jewel Jam game, you want to perform a couple of basic operations on the grid, including
shifting the elements in a row to the left or to the right. For example, when the player drags the
third row in the grid to the left, all elements except the leftmost one should shift to the left, and the
leftmost element becomes the rightmost one. Because this kind of operation isn't something you
need in every game that uses a grid, let's create a class JewelGrid that inherits from GameObjectGrid ,
and then add the operations you need to that class. Here is the constructor method of the
JewelGrid class:
function JewelGrid(rows, columns, layer) {
GameObjectGrid.call(this, rows, columns, layer);
this.dragging = false;
this._dragRow = 0;
this._draggingLastX = 0;
this._touchIndex = 0;
}
JewelGrid.prototype = Object.create(GameObjectGrid.prototype);
It includes a few member variables you need for storing information related to the dragging that the
user is doing. You see more detail later when you learn how to obtain this dragging behavior.
You shift the columns in a row to the left by storing the first element in a temporary object, moving
the other objects one column to the left, and finally placing the element stored in the temporary
object in the last column. You can add a method shiftRowLeft that does exactly this. Because the
method is applied to only one row, you have to pass the row index as a parameter. The complete
method is as follows:
JewelGrid.prototype.shiftRowLeft = function (selectedRow) {
var firstObj = this.at(0, selectedRow);
var positionOffset = firstObj.position.x;
for (var x = 0; x < this._columns - 1; x++) {
this._gameObjects[selectedRow * this._columns + x]
= this._gameObjects[selectedRow * this._columns + x + 1];
}
this._gameObjects[selectedRow * this._columns + (this._columns - 1)] = firstObj;
firstObj.position = new Vector2(this._columns * this.cellWidth + positionOffset,
selectedRow * this.cellHeight);
};
 
Search WWH ::




Custom Search