Game Development Reference
In-Depth Information
if (self.gameLayer.selectedGem ~=
nil) then self.gameLayer.selectedGem:deselect() end
self.gameLayer.selectedGem = nil
self:selectStartGem (touchedGem)
end
end
end
end
We find the gem closest to the touch position. If the user has not selected a gem
yet ( selectedGem = nil ), we set the one just touched as the first gem selec-
ted. Otherwise, we determine whether the second gem selected can be used for a
swap. Only gems above and below the first selected gem, or the ones to the left
and right of it, can be swapped with. If that is valid, we use the second gem as the
target gem.
3. Before moving on to onTouchMove and onTouchUp , let's see how we determ-
ine which gem is being selected and which gem is a valid target gem. So let's
work on the findGemAtPosition value. Begin by determining where in the
grid container the touch landed:
function GridController:findGemAtPosition (position)
local mx = position.x
local my = position.y
local gridWidth = constants.GRID_SIZE_X *
(constants.TILE_SIZE + constants.GRID_SPACE)
local gridHeight = constants.GRID_SIZE_Y *
(constants.TILE_SIZE + constants.GRID_SPACE)
mx = mx -
self.gameLayer.gemsContainer:getPositionX()
my = my -
self.gameLayer.gemsContainer:getPositionY()
if (mx < 0) then mx = 0 end
if (my < 0) then my = 0 end
if (mx > gridWidth) then mx = gridWidth end
if (my > gridHeight) then my = gridHeight end
4. Here is where the magic happens. We use the x and y position of the touch inside
the grid to determine the index of the gem inside the array:
Search WWH ::




Custom Search