- Home /
Hello I'm trying to write a C# about "Pinch to zoom" but it doesn't work
I've set my camera to: -Clear flags: solid color -Projection: Orthographic
This is my C#: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PZoom : MonoBehaviour { float previousDistance; float zoomSpeed = 1.0f;
// Update is called once per frame
void Update()
{
if(Input.touchCount == 2 &&
(Input.GetTouch(0).phase == TouchPhase.Began ||
Input.GetTouch(1).phase == TouchPhase.Began))
{
//calibrate distance
previousDistance = Vector2.Distance(Input.GetTouch(0).position, Input.GetTouch(1).position);
}
else if (Input.touchCount == 2 &&
(Input.GetTouch(0).phase == TouchPhase.Moved||
Input.GetTouch(1).phase == TouchPhase.Moved))
{
float distance;
Vector2 touch1 = Input.GetTouch(0).position;
Vector2 touch2 = Input.GetTouch(1).position;
distance = Vector2.Distance(touch1, touch2);
//camera based on pinch/zoom
float pinchAmount = (previousDistance - distance) * zoomSpeed * Time.deltaTime;
if (Camera.main.orthographic)
{
Camera.main.orthographicSize += pinchAmount;
}
else
{
Camera.main.transform.Translate(0,0,pinchAmount);
}
previousDistance = distance;
}
}
}
Thanks very much to help me!!
Comment
Answer by JonPQ · Aug 27, 2019 at 12:15 AM
logic looks pretty good. put a breakpoint on this line...
float pinchAmount = (previousDistance - distance) * zoomSpeed * Time.deltaTime;
To check what all the values are when doing a 2 finger pinch. make sure neither zoomSpeed or Time.deltaTime are 0 only other thing I can think of, is its not using finger index 0 and 1 for some reason. You can also add some debug logs, to make sure the distance is actually changing , just log the distance. Tat should help you track down the issue.