- Home /
Setting pivot to the middle of two touches - 2D project
I have the following code which works perfectly for both PinchZoom and ScrollZoom on the object it is attatched to.
My problem is that PinchZoom always zooms focusing the center of the image because my object is scaling up and down to simulate the zoom effect and it does it from it's pivot location which is in the center in this case.
I wonder if there is a way to set the pivot point to the middle of two touches in order to zoom from the middle of the fingers.
using UnityEngine;
using UnityEngine.EventSystems;
public class UIZoomImage : MonoBehaviour, IScrollHandler
{
private Vector3 initialScale;
[SerializeField]
private float zoomSpeed = 0.1f;
[SerializeField]
private float maxZoom = 10f;
public float zoomSpeedOnTouch = 0.01f;
private void Awake(){
initialScale = transform.localScale;
}
void Update(){
if(Input.touchCount == 2){
Touch touchZero = Input.GetTouch(0);
Touch touchOne = Input.GetTouch(1);
// FIND PREVIOUS FRAME POSITION OF EACH TOUCH AND STORING IT IN A VECTOR2 VARIABLE BY SUBSTRACTING DELTA POSITION FROM CURRENT POSITION
Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
// STORE IN A FLOAT THE MAGNITUDE OF THE VECTOR DRAWN BETWEEN THE 2 TOUCHES IN EACH FRAME IF CURRENT BIGGER THAN LAST FRAME WE ZOOM IN IF CURRENT SMALLER WE ZOOM OUT
float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
float TouchDeltaMag = (touchZero.position - touchOne.position).magnitude;
// FIND DIFFERENCE BETWEEN THE PREVIOUS FRAME VECTOR AND THE CURRENT FRAME VECTOR, STORE THE DIFFERENCE IN A FLOAT VARIABLE. WE WILL SUBSTRACT THE CURRENT VECTOR FROM THE PREVIOUS ONE
float deltaMagnitudeDifference = prevTouchDeltaMag - TouchDeltaMag;
// IF DELTA MAGNITUDE DIFFERENCE IS A NEGATIVE VALUE IT MEANS FINGERS ARE MOVING APART, THEREFORE WE ZOOM IN
if(deltaMagnitudeDifference != 0){
Vector3 delta = Vector3.one * (deltaMagnitudeDifference * zoomSpeedOnTouch);
Vector3 desiredScale = transform.localScale - delta;
desiredScale = ClampDesiredScale(desiredScale);
transform.localScale = desiredScale;
}
}
}
//SCROLL ZOOM IN
public void OnScroll(PointerEventData eventData){
Vector3 delta = Vector3.one * (eventData.scrollDelta.y * zoomSpeed);
Vector3 desiredScale = transform.localScale + delta;
desiredScale = ClampDesiredScale(desiredScale);
transform.localScale = desiredScale;
}
private Vector3 ClampDesiredScale(Vector3 desiredScale){
desiredScale = Vector3.Max(initialScale, desiredScale);
desiredScale = Vector3.Min(initialScale * maxZoom, desiredScale);
return desiredScale;
}
}
Comment