How to add a Minimum and Maximum to pinch zoom touch script
using UnityEngine;
public class PinchZoom : MonoBehaviour { public float perspectiveZoomSpeed = 0.5f; // The rate of change of the field of view in perspective mode. public float orthoZoomSpeed = 0.5f; // The rate of change of the orthographic size in orthographic mode.
void Update()
{
// If there are two touches on the device...
if (Input.touchCount == 2)
{
// Store both touches.
Touch touchZero = Input.GetTouch(0);
Touch touchOne = Input.GetTouch(1);
// Find the position in the previous frame of each touch.
Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
// Find the magnitude of the vector (the distance) between the touches in each frame.
float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
// Find the difference in the distances between each frame.
float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
// If the camera is orthographic...
if (GetComponent<Camera>().orthographic)
{
// ... change the orthographic size based on the change in distance between the touches.
GetComponent<Camera>().orthographicSize += deltaMagnitudeDiff * orthoZoomSpeed;
// Make sure the orthographic size never drops below zero.
GetComponent<Camera>().orthographicSize = Mathf.Max(GetComponent<Camera>().orthographicSize, 0.1f);
}
else
{
// Otherwise change the field of view based on the change in distance between the touches.
GetComponent<Camera>().fieldOfView += deltaMagnitudeDiff * perspectiveZoomSpeed;
// Clamp the field of view to make sure it's between 0 and 180.
GetComponent<Camera>().fieldOfView = Mathf.Clamp(GetComponent<Camera>().fieldOfView, 0.1f, 179.9f);
}
}
}
}
Comment
Answer by andycodes · May 13, 2017 at 07:38 PM
Well this is super old, but I was just doing the same thing and found the solution to this issue using the same script:
public float maxZoom = 10f; //farthest you can get
public float minZoom = 2f; //closest you can get
void Update()
{
//...
// If the camera is orthographic...
if (GetComponent<Camera>().orthographic)
{
// ... change the orthographic size based on the change in distance between the touches.
float i = GetComponent<Camera>().orthographicSize + deltaMagnitudeDiff * orthoZoomSpeed;
if( i >= maxZoom){ //if i is greater than maxZoom, set camera to max
GetComponent<Camera>().orthographicSize = maxZoom;
}
else if ( i <= minZoom){ //same but with min
GetComponent<Camera>().orthographicSize = minZoom;
}
else{ //otherwise just update it to i
GetComponent<Camera>().orthographicSize = i;
}
//...
}
}
}
Answer by cmcosby · Jan 14, 2018 at 02:40 AM
What about a perspective camara??
Simply change the maximum and $$anonymous$$imum field of view here. :)
GetComponent().fieldOfView = $$anonymous$$athf.Clamp(GetComponent().fieldOfView, 0.1f, 179.9f);