AndroidTouch.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using UnityEngine;
  2. using System.Collections;
  3. public class AndroidTouch : MonoBehaviour
  4. {
  5. private int isforward;//标记摄像机的移动方向
  6. //记录两个手指的旧位置
  7. private Vector2 oposition1 = new Vector2();
  8. private Vector2 oposition2 = new Vector2();
  9. Vector2 m_screenPos = new Vector2(); //记录手指触碰的位置
  10. //用于判断是否放大
  11. bool isEnlarge(Vector2 oP1, Vector2 oP2, Vector2 nP1, Vector2 nP2)
  12. {
  13. //函数传入上一次触摸两点的位置与本次触摸两点的位置计算出用户的手势
  14. float leng1 = Mathf.Sqrt((oP1.x - oP2.x) * (oP1.x - oP2.x) + (oP1.y - oP2.y) * (oP1.y - oP2.y));
  15. float leng2 = Mathf.Sqrt((nP1.x - nP2.x) * (nP1.x - nP2.x) + (nP1.y - nP2.y) * (nP1.y - nP2.y));
  16. if (leng1 < leng2)
  17. {
  18. //放大手势
  19. return true;
  20. }
  21. else
  22. {
  23. //缩小手势
  24. return false;
  25. }
  26. }
  27. void Start()
  28. {
  29. Input.multiTouchEnabled = true;//开启多点触碰
  30. }
  31. void Update()
  32. {
  33. if (Input.touchCount <= 0)
  34. return;
  35. if (Input.touchCount == 1) //单点触碰移动摄像机
  36. {
  37. if (Input.touches[0].phase == TouchPhase.Began)
  38. m_screenPos = Input.touches[0].position; //记录手指刚触碰的位置
  39. if (Input.touches[0].phase == TouchPhase.Moved) //手指在屏幕上移动,移动摄像机
  40. {
  41. transform.Translate(new Vector3(Input.touches[0].deltaPosition.x * Time.deltaTime, Input.touches[0].deltaPosition.y * Time.deltaTime, 0));
  42. }
  43. }
  44. else if (Input.touchCount > 1)//多点触碰
  45. {
  46. //记录两个手指的位置
  47. Vector2 nposition1 = new Vector2();
  48. Vector2 nposition2 = new Vector2();
  49. //记录手指的每帧移动距离
  50. Vector2 deltaDis1 = new Vector2();
  51. Vector2 deltaDis2 = new Vector2();
  52. for (int i = 0; i < 2; i++)
  53. {
  54. Touch touch = Input.touches[i];
  55. if (touch.phase == TouchPhase.Ended)
  56. break;
  57. if (touch.phase == TouchPhase.Moved) //手指在移动
  58. {
  59. if (i == 0)
  60. {
  61. nposition1 = touch.position;
  62. deltaDis1 = touch.deltaPosition;
  63. }
  64. else
  65. {
  66. nposition2 = touch.position;
  67. deltaDis2 = touch.deltaPosition;
  68. if (isEnlarge(oposition1, oposition2, nposition1, nposition2)) //判断手势伸缩从而进行摄像机前后移动参数缩放效果
  69. isforward = 1;
  70. else
  71. isforward = -1;
  72. }
  73. //记录旧的触摸位置
  74. oposition1 = nposition1;
  75. oposition2 = nposition2;
  76. }
  77. //移动摄像机
  78. Camera.main.transform.Translate(isforward * Vector3.forward * Time.deltaTime * (Mathf.Abs(deltaDis2.x + deltaDis1.x) + Mathf.Abs(deltaDis1.y + deltaDis2.y)));
  79. }
  80. }
  81. }
  82. }