I have a canvas drawing which is using OnTouch, however for some reason I cannot get this to work properly. It works for the first time (the first touch movement). However when the user removes his finger the OnTouch never runs again, stopping the user from moving the character item.
Having done lots of research and various different options, I simply cannot get this to work and in doing so have noticed that ACTION_DOWN is called for the first time then on ACTION_UP is called.
Below you can find my 2 chunks of code, the first is the actual onTouchEvent. The second the chunck of code used to handle the user permission within my drawn canvas (which is maze(5 x 5) based).
Another nore to consider is the canvas is redrawn (invalidate), everytime the user position is moved (this is done square by square)
@Override
public boolean onTouchEvent(MotionEvent event)
{
float touchX = event.getX();
float touchY = event.getY();
int currentX = maze.getCurrentX();
int currentY = maze.getCurrentY();
switch (event.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
if(Math.floor(touchX/totalCellWidth) == currentX && Math.floor(touchY/totalCellHeight) == currentY)
{
dragging = true;
return true;
}
break;
case MotionEvent.ACTION_UP:
dragging = false;
break;
case MotionEvent.ACTION_MOVE:
if(dragging)
{
int cellX = (int)Math.floor(touchX/totalCellWidth);
int cellY = (int)Math.floor(touchY/totalCellHeight);
if((cellX != currentX && cellY == currentY) || (cellY != currentY && cellX == currentX))
{
boolean moved = false;
switch(cellX-currentX)
{
case 1:
moved = maze.move(Maze.RIGHT);
break;
case -1:
moved = maze.move(Maze.LEFT);
}
switch(cellY-currentY)
{
case 1:
moved = maze.move(Maze.DOWN);
break;
case -1:
moved = maze.move(Maze.UP);
}
if(moved)
{
invalidate();
if(maze.isGameComplete())
{
showFinishDialog();
}
}
}
break;
}
}
return true;
}
The maze position handler code:
public boolean move(int direction)
{
boolean moved = false;
if(direction == UP)
{
if(currentY != 0 && !horizontalLines[currentY-1][currentX])
{
currentY--;
moved = true;
}
}
if(direction == DOWN)
{
if(currentY != verticalLines[0].length-1 && !horizontalLines[currentY][currentX])
{
currentY++;
moved = true;
}
}
if(direction == RIGHT)
{
if(currentX != horizontalLines[0].length-1 && !verticalLines[currentY][currentX])
{
currentX++;
moved = true;
}
}
if(direction == LEFT)
{
if(currentX != 0 && !verticalLines[currentY][currentX-1])
{
currentX--;
moved = true;
}
}
if(moved)
{
if(currentX == finalX && currentY == finalY)
{
gameComplete = true;
}
}
return moved;
}