AndroidTouch.cs 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.EventSystems;
  4. public class AndroidTouch : MonoBehaviour
  5. {
  6. private Vector3 DefaultPostion;
  7. private float addValue;
  8. private float scale;
  9. private const float maxDis = 6;
  10. private Touch oldTouch1; //上次触摸点1(手指1)
  11. private Touch oldTouch2; //上次触摸点2(手指2)
  12. private void Start()
  13. {
  14. DefaultPostion = this.transform.position;
  15. }
  16. void Update()
  17. {
  18. //没有触摸,就是触摸点为0
  19. if (Input.touchCount <= 0)
  20. {
  21. return;
  22. }
  23. //单点触摸, 水平上下旋转
  24. if (1 == Input.touchCount)
  25. {
  26. Touch touch = Input.GetTouch(0);
  27. Vector2 deltaPos = touch.deltaPosition/ 2;
  28. if (touch.position.x < Screen.width / 2)
  29. {
  30. transform.Rotate(Vector3.down * deltaPos.x, Space.Self);//绕Y轴进行旋转
  31. }
  32. else
  33. {
  34. transform.Rotate(Vector3.right * deltaPos.y, Space.Self);//绕X轴进行旋转,下面我们还可以写绕Z轴进行旋转
  35. }
  36. return;
  37. }
  38. //多点触摸, 放大缩小
  39. Touch newTouch1 = Input.GetTouch(0);
  40. Touch newTouch2 = Input.GetTouch(1);
  41. //第2点刚开始接触屏幕, 只记录,不做处理
  42. if (newTouch2.phase == TouchPhase.Began)
  43. {
  44. oldTouch2 = newTouch2;
  45. oldTouch1 = newTouch1;
  46. //addValue = 0;
  47. return;
  48. }
  49. //计算老的两点距离和新的两点间距离,变大要放大模型,变小要缩放模型
  50. float oldDistance = Vector2.Distance(oldTouch1.position, oldTouch2.position);
  51. float newDistance = Vector2.Distance(newTouch1.position, newTouch2.position);
  52. //两个距离之差,为正表示放大手势, 为负表示缩小手势
  53. float offset = newDistance - oldDistance;
  54. //放大因子, 一个像素按 0.01倍来算(100可调整)
  55. float scaleFactor = - offset / 100f;
  56. addValue += scaleFactor;
  57. Vector3 localScale = transform.localScale;
  58. Vector3 scale = new Vector3(localScale.x + scaleFactor,
  59. localScale.y + scaleFactor,
  60. localScale.z + scaleFactor);
  61. //在什么情况下进行缩放
  62. if (addValue < maxDis && addValue >0)
  63. {
  64. this.transform.position = DefaultPostion + Vector3.forward * addValue;
  65. }
  66. else
  67. {
  68. CDebug.Log(scale.ToString() + "-->" + addValue);
  69. }
  70. if (addValue > maxDis)
  71. {
  72. addValue = maxDis;
  73. }
  74. else if (addValue < 0)
  75. {
  76. addValue = 0;
  77. }
  78. //记住最新的触摸点,下次使用
  79. oldTouch1 = newTouch1;
  80. oldTouch2 = newTouch2;
  81. }
  82. public void RefreshPos()
  83. {
  84. CDebug.Log("RefreshPos");
  85. this.transform.position = DefaultPostion;
  86. //this.transform.eulerAngles = FollowTarget.eulerAngles.y * Vector3.up;
  87. this.transform.position +=Vector3.forward * scale;
  88. //this.transform.localScale = this.transform.localScale * scale;
  89. }
  90. }