I'm trying to implement pinch zoom, the zoom is working but it always zooming to the centre of the RectTransform, I tried to calculate the centre between the fingers and move to that point with DOAnchorPos but it takes me out of the RectTransform
here is how I calculate the centre and tried to move to it:
Vector3 center = (touchZero + touchOne) / 2f;
content.DOAnchorPos(center, 0.3f);
And here is the zoom that works:
public class PinchZoom : MonoBehaviour
{
public RectTransform content;
private void Update()
{
if (Input.touchCount != 2) return;
var touchZero = Input.GetTouch(0);
var touchOne = Input.GetTouch(1);
var touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
var touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
var prevMagnitude = (touchZeroPrevPos - touchOnePrevPos).magnitude;
var currentMagnitude = (touchZero.position - touchOne.position).magnitude;
var difference = prevMagnitude - currentMagnitude;
var localScale1 = content.localScale;
var scale = localScale1;
var localScale = scale;
var zoomX = Mathf.Clamp(localScale.x - difference * 0.01f, 0.9f, 7f);
var zoomY = Mathf.Clamp(localScale.y - difference * 0.01f, 0.9f, 7f);
content.DOScale(new Vector3(zoomX, zoomY, 1f), 0.1f);
}
}
I found code in this question by ArtS but it didn't quite work for me if I used a perspective camera. With some substantial tweaks I think it works pretty well: