- Home /
How to scroll/drag multiple ui images simultaneously?
I've two similar UI images inside canvas one under the other, they are independent gameobjects. Since the images are big size each has a parent with Scrollrect + Mask and has a child UI image with pinch zoom script attached. I want both of them to have a zoom capability but within their own boundaries. Since i attached the script to both of them, zoom capability is working fine, when i pinch on mobile device both zoom simultaneously. But after zoom stopped, i also want to drag/scroll both of these images simultaneously. Scrollrect is working fine for this but only the touched image is scrolling, the other is not scrolling, which i don't want. How can i scroll both of them simultaneously in the same way (something like if one is scrolling, scroll the other one in the same way)
Here is my script for pinch zoom:
public class PinchZoom : MonoBehaviour
{
[SerializeField] float zoomSpeed = 0.1f;
[SerializeField] float maxZoom = 5f;
[SerializeField] ScrollRect scrollRect;
private Vector3 initialScale;
private void Awake()
{
initialScale = transform.localScale;
}
void Update()
{
// If there are two touches on the device...
if (Input.touchCount == 2)
{
// Disable scrolling while pinch
scrollRect.enabled = false;
// Store both touches.
Touch firstTouch = Input.GetTouch(0);
Touch secondTouch = Input.GetTouch(1);
// Find the position of each touch in the previous frame.
Vector2 firstTouchPrevPos = firstTouch.position - firstTouch.deltaPosition;
Vector2 secondTouchPrevPos = secondTouch.position - secondTouch.deltaPosition;
// Find the magnitude of the vector (the distance) between the touches in each frame.
float prevTouchDeltaMag = (firstTouchPrevPos - secondTouchPrevPos).magnitude;
float currTouchDeltaMag = (firstTouch.position - secondTouch.position).magnitude;
// Find the difference in the distances between each frame.
float deltaMagnitudeDiff = currTouchDeltaMag - prevTouchDeltaMag;
// create a vector from the change amount
var delta = Vector3.one * (deltaMagnitudeDiff * zoomSpeed * Time.deltaTime);
// rescale the image, but clamp the scale
var desiredScale = transform.localScale + delta;
desiredScale = ClampDesiredScale(desiredScale);
transform.localScale = desiredScale;
}
else
// Enable scrolling
scrollRect.enabled = true;
}
private Vector3 ClampDesiredScale(Vector3 desiredScale)
{
desiredScale = Vector3.Max(initialScale, desiredScale);
desiredScale = Vector3.Min(initialScale * maxZoom, desiredScale);
return desiredScale;
}
}
Your answer
Follow this Question
Related Questions
Re-center UI Image after zooming out 0 Answers
Use UI buttons with Time.timeScale=0? 3 Answers
Why use different Canvas Render Modes 0 Answers
Can't get UI Canvas to overlay the scene 2 Answers
How to scale according to different mobile resolutions? 0 Answers