From Zero to App

Check part 1 first in case you’ve missed that!

In the second part we will generate a grid movement.

Current code

Your current files should look like this

Grid movement

The idea is that we have define a grid size and only move the view if our x/y position is greater than half of the grid size.

Create two variables to store the grid size and half of it (then we don’t need to calculate it all the time)

Then we update our onTouchmove method. First store the position that we assigned to the activeItem before:

Next we need to see if our posX/posY is before or after halfGridSize. To do that we use the module operator:

if this is true we move one gridSize right, if false we stay at our previous grid position.

To stay at the grid location we simply subtract the modulo value from posX. To jump to the next grid position we add gridSize. The full movement code will look like this now:

Now we use this value and assign it to our current item

When dragging the view it will now move in our grid structure.

Final code