This is the function I wrote that is doing the snapping
The endFoundBlockPos position is set when the touchEnds and the
startFoundBlockPos is set when we start the touch and we found the
block before you move the block get the starting position.
Also these values should be assigned according to the direction in
which the block is moving. If the block is moving verticaly for
example startFoundBlockPos = FoundBlock.y and when the touch ends
endFoundBlockPos = FoundBlockPos.y; then I get the difference of the
two. The take the difference divide it with 50, since we know that the
the field is 300 by 300 and out blocks are have the maximum width and
height of 150. So if I divide the difference by 50 and there is no
remeinder I know that the block has been moved by 50 or 100 or 150
then I just need to add the difference to the startFoundBlockPos
andset the block pos to that depending on the direction it is moving.
If there is a remender I have to check how much is the remeinder if
the remeinder is less than 24 I just ignore it if it is greater than
24 I take the difference divide by 50 muiltiply by 50 then add
startFoundBlockPos plus 50. Any way go through the code and try to
understand it.. This function is called as soon as the touchends in
the touchends function and after you set endFoundBlockPos but before
you set the FoundBlock = 0;
Like this:
endFoundBlockPos = FoundBlock.x or y depending on direction.
[self.snapBlock: FoundBlock];
FoundBlock = 0;
endFoundBlockPos = 0;
startFoundBlockPos = 0;
-(void) snapBlock:(Block *) inBlock
{
int diff;
float foundBlockNewPos;
diff = (endFoundBlockPos - startFoundBlockPos);
if(diff % 50 == 0)
{
foundBlockNewPos = (startFoundBlockPos + (endFoundBlockPos -
startFoundBlockPos));
NSLog(@" No remeinder");
}
else if(diff % 50 !=0 )
{
if (diff % 50 <= 24 && diff % 50 > 0)
{
if ((diff % 50) > 24)
{
foundBlockNewPos = (((diff/50)*50) + startFoundBlockPos + 50);
}
else
{
foundBlockNewPos = (((diff/50)*50) + startFoundBlockPos);
}
NSLog(@" remeinder inside less not less 0: %i\n", diff % 50);
}
else if (diff % 50 <= 24 && diff % 50 < 0)
{
if ((-(diff % 50)) > 24)
{
foundBlockNewPos = (((diff/50)*50) + startFoundBlockPos - 50);
}
else
{
foundBlockNewPos = (((diff/50)*50) + startFoundBlockPos);
}
NSLog(@" remeinder inside less 0: %i\n", diff % 50);
}
else if (diff % 50 > 24) {
foundBlockNewPos = (((diff/50)*50) + startFoundBlockPos + 50);
NSLog(@" remeinder inside greater");
}
}
if (inBlock.dir == Horiz_BLK)
{
NSLog(@" MOVING IN X");
inBlock.x = foundBlockNewPos;
}
if (inBlock.dir == Vert_BLK)
{
NSLog(@" MOVING IN Y");
inBlock.y = foundBlockNewPos;
}