I'm programming Snake on Android with Android Studio 2.3.2
And in order to move the snake i've made an onTouchListener to detect if the user is swiping and in which direction (North, South, East, West)
In the following is the onTouch method of View.onTouchListener:
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
prevX = event.getX();
prevY = event.getY();
break;
case MotionEvent.ACTION_UP:
float newX = event.getX();
float newY = event.getY();
//Calculates where we swiped
if (Math.abs(newX - prevX) > Math.abs(newY - prevY)) {
//LEFT - RiGHT Direction
if( newX > prevX) {
//RIGHT
gameEngine.updateDirection(Direction.East);
} else {
//LEFT
gameEngine.updateDirection(Direction.West);
}
} else {
// UP-DOWN Direction
if (newY > prevY) {
//DOWN
gameEngine.updateDirection(Direction.South);
} else {
//UP
gameEngine.updateDirection(Direction.North);
}
}
break;
}
return false;
}
The problem is that it only detects LEFT and RIGHT (so EAST and WEST). And i don't know why UP and DOWN doesn't get detected.