Game Development Reference
In-Depth Information
In addition to moving the leftmost element to the rightmost column and shifting all the other
elements, you change the position of the object that was changed from being the leftmost object to
the rightmost object. You take into account any existing position offset of the first element by storing
it in a local variable before you perform the shifting operation and then adding that offset to the new
position. The result of this positional change is a nice motion effect, as you'll see later. The method
shiftRowRight is similar to this method; see the example code for JewelJam3 .
You also want to add a method that gives you the anchor position in the grid for any game object.
This method will be useful later. As a parameter, this method expects a game object, and it returns a
Vector2 object containing the anchor position. Here is the complete method:
GameObjectGrid.prototype.getAnchorPosition = function (gameobject) {
var l = this._gameObjects.length;
for (var i = 0; i < l; i++)
if (this._gameObjects[i] === gameobject) {
var row = Math.floor(i / this.columns);
var col = i % this.columns;
return new Vector2(col * this.cellWidth, row * this.cellHeight);
}
return Vector2.zero;
};
This method uses a for instruction to look for the game object that was passed as a parameter. Once
this object has been found, you calculate its anchor position based on the row and column indices in the
grid, together with the cell size. If the object wasn't found, you return the zero vector ( Vector2.Zero ).
Because this method is useful for almost all grids, you add it to the GameObjectGrid class.
Moving Smoothly on the Grid
To make objects move smoothly on the grid, you can use the velocity and position member
variables that are part of the GameObject class. You use the anchor position retrieved from the
GameObjectGrid instance to calculate the velocity of the game object belonging at that position. The
effect is that when the game object isn't exactly at the anchor position, it automatically starts moving
toward that position.
To do this, you introduce another class called Jewel , which represents a game object in the grid (in
this case, a kind of jewel). This game object is a subclass of SpriteGameObject . In the constructor of
this class, you randomly select one of the three jewel sprites, as follows:
function Jewel(layer) {
var randomval = Math.floor(Math.random() * 3) + 1;
var spr = sprites["single_jewel" + randomval];
SpriteGameObject.call(this, spr, layer);
}
 
Search WWH ::




Custom Search