- Home /
Question by
VariantPolygon · Mar 18, 2021 at 02:08 PM ·
c#mousepositionuser interface2d spriteszoom-in
Zooming in on UI image using mouse cursor position
I'm using this script along with the built in 'ScrollRect' and 'RectMask2d' to zoom in on a UI image for a world map in my game using the mouse scroll wheel. I'm wondering if there is a way to zoom in on the position of the cursor instead of zooming in at the images pivot?
using UnityEngine;
using UnityEngine.EventSystems;
public class UIZoomImage : MonoBehaviour, IScrollHandler
{
private Vector3 initialScale;
[SerializeField]
private float zoomSpeed = 0.1f;
[SerializeField]
private float maxZoom = 10f;
private void Awake()
{
initialScale = transform.localScale;
}
public void OnScroll(PointerEventData eventData)
{
var delta = Vector3.one * (eventData.scrollDelta.y * zoomSpeed);
var 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
Your answer
Follow this Question
Related Questions
[Solved] Constraining a position within a radius (2D crosshair) 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Get text from UI when collected play sound. 0 Answers
C# - How to find the mouse position? 0 Answers