Game Development Reference
In-Depth Information
The only other thing you need to change in this game object is the update method, because drawing
the sprite is already properly handled in the base class. What needs to be done in the update
method? First you need to call the original version of the update method so the position of the object
is always updated according to its velocity:
SpriteGameObject.prototype.update.call(this, delta);
Then you need to find out the anchor position of this game object. You can do this by calling
getAnchorPosition from the parent (which normally should be a JewelGrid instance):
var anchor = this.parent.getAnchorPosition(this);
And finally, you modify the velocity of the game object so it moves toward the anchor position:
this.velocity = anchor.subtractFrom(this.position).multiplyWith(15);
As you can see, you calculate the velocity by taking the difference between the target position
(which is the anchor position) and the current position. To get a faster motion effect, you multiply
this value by 15. When the game object's position is updated, this velocity is added to the position
vector, and as a result the game object moves toward the target position. For the complete Jewel
class, see the JewelJam3 example.
Dragging Rows in the Grid
The final thing you do in this chapter is add dragging behavior to the grid so the player can move
rows to the left and to the right. You define the dragging behavior in two steps. First you determine
what the new position of the elements in the row should be, depending on where the player is
dragging with the mouse or their finger. Then, depending on how far the player has dragged the row,
you shift elements to the left or to the right.
You define this dragging behavior for both mouse and touch input. Therefore, you split the
handleInput method into two parts, each defined in a specific method for the type of input:
JewelGrid.prototype.handleInput = function (delta) {
if (Touch.isTouchDevice)
this.handleInputTouch(delta);
else
this.handleInputMouse(delta);
};
Because the dragging behavior is specific to the Jewel Jam game, you handle the input in
JewelGrid . Let's look at mouse dragging behavior first. You need to detect that the player has
started dragging in the grid. This is only possible if the left mouse button is down and the player isn't
yet dragging. If that is the case, you need to determine whether the player is dragging in the grid or
 
Search WWH ::




Custom Search