改寫Android的Snake例子,使之運行於我的三星手機上。判斷規則如下:如果x方向移動距離大於y方向,則認為是水平移動,反之則是上下移動。如果水平移動,x移動正距離x-x0>0 則認為向右移動,負距離x-x0<0 則認為向左移動;上下移動的判斷同理。
代碼如下,需要注意的是MotionEvent的ACTION_DOWN, ACTION_UP 是這麼理解的:
ACTION_DOWN - A pressed gesture has started, the motion contains the initial starting location.
ACTION_UP - A pressed gesture has finished, the motion contains the final release location as well as any intermediate points since the last down or move event.
ACTION_MOVE - A change has happened during a press gesture (between {@link #ACTION_DOWN} and {@link #ACTION_UP}). The motion contains the most recent point, as well as any intermediate points since the last down or move event. -
簡而言之,ACTION_DOWN, ACTION_UP 類似於Javascript裡面鍵盤事件OnKeyDown, OnKeyUp 或鼠標事件OnMouseDown, OnMouseUp, 而不是說手指往上劃拉或往下劃拉了一下。
- /**
- * Re write onKeyDown() for SAMSUNG
- */
- public boolean onTouchEvent(MotionEvent event) {
- // Set the game status to running
- if (event.getAction() == MotionEvent.ACTION_DOWN) {
- if (mMode == READY | mMode == LOSE) {
- initNewGame();
- setMode(RUNNING);
- update();
- return true;
- }
-
- if (mMode == PAUSE) {
- setMode(RUNNING);
- update();
- return true;
- }
- }
-
- float x = event.getX();
- float y = event.getY();
-
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- mX = x;
- mY = y;
- update();
- return true;
- case MotionEvent.ACTION_UP:
- float dx = x - mX;
- float dy = y - mY;
- if (Math.abs(dx) >= TOUCH_TOLERANCE
- || Math.abs(dy) >= TOUCH_TOLERANCE) {
-
- if (Math.abs(dx) >= Math.abs(dy)) { // move from left -> right
- // or right -> left
- if (dx > 0.0f) {
- turnTo(EAST);
- } else {
- turnTo(WEST);
- }
-
- } else { // move from top -> bottom or bottom -> top
- if (dy > 0.0f) {
- turnTo(SOUTH);
- } else {
- turnTo(NORTH);
- }
- }
- update();
- return true;
- }
- }
-
- return super.onTouchEvent(event);
- }
-
- private void turnTo(int direction) {
- if (direction == WEST & mDirection != EAST) {
- mNextDirection = WEST;
- }
-
- if (direction == EAST & mDirection != WEST) {
- mNextDirection = EAST;
- }
-
- if (direction == SOUTH & mDirection != NORTH) {
- mNextDirection = SOUTH;
- }
-
- if (direction == NORTH & mDirection != SOUTH) {
- mNextDirection = NORTH;
- }
- }