Pinch zoom on UI
Hi everybody, I use this script made by unity for pinch zoom, but I can't zoom in or out the UI in my canvas. How could I do please ?
https://unity3d.com/fr/learn/tutorials/topics/mobile-touch/pinch-zoom
Comment
Best Answer
Answer by spraw · Nov 14, 2016 at 05:51 AM
Hey. Hope this works for you:
using UnityEngine;
public class PinchZoom : MonoBehaviour
{
public Canvas canvas; // The canvas
public float zoomSpeed = 0.5f; // The rate of change of the canvas scale factor
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;
// ... change the canvas size based on the change in distance between the touches.
canvas.scaleFactor -= deltaMagnitudeDiff * zoomSpeed;
// Make sure the canvas size never drops below 0.1
canvas.scaleFactor = Mathf.Max(canvas.scaleFactor, 0.1f);
}
}
}
I just slightly edited the original tutorial source code. Remember to assign the canvas in the inspector. You may have to play around with the numbers ;)
This code is just zoo$$anonymous$$g. Is it possible to add Pan to this code?
It works perfectly for me but it does not respect the boundaries of my device display. It moves out of the UI while dragging. Do you have any suggestion how to fix this?
Your answer