PinchZoom.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class PinchZoom : MonoBehaviour
  5. {
  6. public float perspectiveZoomSpeed = 0.5f;
  7. public float orthoZoomSpeed = 0.5f;
  8. // Update is called once per frame
  9. void Update() {
  10. // If there are two touches on the device...
  11. if (Input.touchCount == 2) {
  12. // Store both touches.
  13. Touch touchZero = Input.GetTouch(0);
  14. Touch touchOne = Input.GetTouch(1);
  15. // Find the position in the previous frame of each touch.
  16. Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
  17. Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
  18. // Find the magnitude of the vector (the distance) between the touches in each frame.
  19. float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
  20. float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
  21. // Find the difference in the distances between each frame.
  22. float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
  23. Camera camera = GetComponent<Camera>();
  24. // If the camera is orthographic...
  25. if (camera.orthographic) {
  26. // ... change the orthographic size based on the change in distance between the touches.
  27. camera.orthographicSize += deltaMagnitudeDiff * orthoZoomSpeed;
  28. // Make sure the orthographic size never drops below zero.
  29. camera.orthographicSize = Mathf.Max(camera.orthographicSize, 0.1f);
  30. } else {
  31. // Otherwise change the field of view based on the change in distance between the touches.
  32. camera.fieldOfView += deltaMagnitudeDiff * perspectiveZoomSpeed;
  33. // Clamp the field of view to make sure it's between 0 and 180.
  34. camera.fieldOfView = Mathf.Clamp(camera.fieldOfView, 0.1f, 179.9f);
  35. }
  36. }
  37. }
  38. }