Game Development Reference
In-Depth Information
outside it. In the latter case, you don't need to do anything. In the former case, you need to store
some information related to where the player is dragging. Here is the complete code:
if (Mouse.left.down && !this.dragging) {
var rect = new Rectangle(this.worldPosition.x, this.worldPosition.y, this.columns *
this.cellHeight, this.rows * this.cellWidth);
if (Mouse.containsMouseDown(rect)) {
this.dragging = true;
this._dragRow = Math.floor((Mouse.position.y - this.worldPosition.y) / this.cellHeight);
this._draggingLastX = Mouse.position.x - this.worldPosition.x;
}
}
You use the dragging variable to keep track of whether the player is dragging. If the player has
started dragging, you calculate which row the player is dragging, and you store that in the _dragRow
member variable. Finally, you calculate the local x-position in the grid of where the mouse currently
is dragging. This will be useful later when you reposition all the jewels according to how much the
player has dragged.
Next you check the second case, where the player isn't dragging. If that is the case, you set the
dragging variable to false :
if (!Mouse.left.down) {
this.dragging = false;
}
Now that you've performed the preparatory step to determine whether the player is dragging,
you need to take action if the player is indeed dragging. The first step is to reposition the jewels
according to how much the player has dragged the row to the left or right. Calculate the new
position of the mouse:
var newpos = Mouse.position.x - this.worldPosition.x;
Then reposition each jewel in the row by adding the difference between the new position and the last
dragging position to the x -coordinate of each jewel:
for (var i = 0; i < this.columns; i++) {
var currObj = this.at(i, this._dragRow);
currObj.position.x += (newpos - this._draggingLastX);
}
Now you check whether you need to shift a row to the left or to the right. You first check whether the
leftmost object has been dragged more than half the width of the cell to the left. You can determine
whether the player is dragging to the left by checking whether newpos is smaller than the last x -
position while dragging. If that is the case, you shift the row to the left:
var firstObj = this.at(0, this._dragRow);
if (firstObj.position.x < -this.cellWidth / 2 && newpos - this._draggingLastX < 0)
this.shiftRowLeft(this._dragRow);
Search WWH ::




Custom Search