unity3d 触屏多点触控(旋转与缩放)

来源:互联网 发布:重生之网络娱乐txt笔下 编辑:程序博客网 时间:2024/05/16 19:44
Java代码 复制代码 收藏代码
  1. /*
  2. Touch Orbit
  3. Programmed by: Randal J. Phillips (Caliber Mengsk)
  4. Original Creation Date: 12/16/2011
  5. Last Updated: 12/16/2011
  6. Desctiption: Simple orbit by one touch and drag, as well as pinch to zoom with two fingers.
  7. */
  8. var x:float;
  9. var y:float;
  10. var xSpeed:float;
  11. var ySpeed:float;
  12. var pinchSpeed:float;
  13. var distance:float = 10;
  14. var minimumDistance:float = 5;
  15. var maximumDistance:float = 100;
  16. private var touch:Touch;
  17. private var lastDist:float =0;
  18. private var curDist:float =0;
  19. private var gameCamera:Camera;
  20. function Start ()
  21. {
  22. gameCamera = Camera.mainCamera;
  23. }
  24. function Update ()
  25. {
  26. if (Input.GetKeyDown(KeyCode.Escape))
  27. {
  28. Application.Quit();
  29. }
  30. if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
  31. {
  32. //One finger touch does orbit
  33. touch = Input.GetTouch(0);
  34. x += touch.deltaPosition.x * xSpeed * 0.02;
  35. y -= touch.deltaPosition.y * ySpeed * 0.02;
  36. }
  37. if (Input.touchCount > 1 && (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved))
  38. {
  39. //Two finger touch does pinch to zoom
  40. var touch1 = Input.GetTouch(0);
  41. var touch2 = Input.GetTouch(1);
  42. curDist = Vector2.Distance(touch1.position, touch2.position);
  43. if(curDist > lastDist)
  44. {
  45. distance += Vector2.Distance(touch1.deltaPosition, touch2.deltaPosition)*pinchSpeed/10;
  46. }else{
  47. distance -= Vector2.Distance(touch1.deltaPosition, touch2.deltaPosition)*pinchSpeed/10;
  48. }
  49. lastDist = curDist;
  50. }
  51. if(distance <= minimumDistance)
  52. {
  53. //minimum camera distance
  54. distance = minimumDistance;
  55. }
  56. if(distance >= maximumDistance)
  57. {
  58. //maximum camera distance
  59. distance = maximumDistance;
  60. }
  61. //Sets rotation
  62. var rotation = Quaternion.Euler(y, x, 0);
  63. //Sets zoom
  64. var position = rotation * Vector3(0.0, 0.0, -distance) + Vector3(0,0,0);
  65. //Applies rotation and position
  66. transform.rotation = rotation;
  67. transform.position = position;
  68. }
  69. function OnGUI()
  70. {
  71. //Simple output to display the distance from the center
  72. GUI.Label(Rect(0,0,Screen.width, Screen.height),distance.ToString());
  73. }  
原创粉丝点击