歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發教程: 觸摸屏模擬實現方向鍵

Android開發教程: 觸摸屏模擬實現方向鍵

日期:2017/3/1 10:27:19   编辑:Linux編程

改寫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, 而不是說手指往上劃拉或往下劃拉了一下。

  1. /**
  2. * Re write onKeyDown() for SAMSUNG
  3. */
  4. public boolean onTouchEvent(MotionEvent event) {
  5. // Set the game status to running
  6. if (event.getAction() == MotionEvent.ACTION_DOWN) {
  7. if (mMode == READY | mMode == LOSE) {
  8. initNewGame();
  9. setMode(RUNNING);
  10. update();
  11. return true;
  12. }
  13. if (mMode == PAUSE) {
  14. setMode(RUNNING);
  15. update();
  16. return true;
  17. }
  18. }
  19. float x = event.getX();
  20. float y = event.getY();
  21. switch (event.getAction()) {
  22. case MotionEvent.ACTION_DOWN:
  23. mX = x;
  24. mY = y;
  25. update();
  26. return true;
  27. case MotionEvent.ACTION_UP:
  28. float dx = x - mX;
  29. float dy = y - mY;
  30. if (Math.abs(dx) >= TOUCH_TOLERANCE
  31. || Math.abs(dy) >= TOUCH_TOLERANCE) {
  32. if (Math.abs(dx) >= Math.abs(dy)) { // move from left -> right
  33. // or right -> left
  34. if (dx > 0.0f) {
  35. turnTo(EAST);
  36. } else {
  37. turnTo(WEST);
  38. }
  39. } else { // move from top -> bottom or bottom -> top
  40. if (dy > 0.0f) {
  41. turnTo(SOUTH);
  42. } else {
  43. turnTo(NORTH);
  44. }
  45. }
  46. update();
  47. return true;
  48. }
  49. }
  50. return super.onTouchEvent(event);
  51. }
  52. private void turnTo(int direction) {
  53. if (direction == WEST & mDirection != EAST) {
  54. mNextDirection = WEST;
  55. }
  56. if (direction == EAST & mDirection != WEST) {
  57. mNextDirection = EAST;
  58. }
  59. if (direction == SOUTH & mDirection != NORTH) {
  60. mNextDirection = SOUTH;
  61. }
  62. if (direction == NORTH & mDirection != SOUTH) {
  63. mNextDirection = NORTH;
  64. }
  65. }
Copyright © Linux教程網 All Rights Reserved