Created
September 15, 2017 21:37
-
-
Save unity3dcollege/f971cee86b6eb09ad4dafc49050f693c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you want to take current mouse position into account, you have to modify OnScroll method like:
That way it will zoom where the mouse is rather than just at the center of the container.
Also make sure that
Scroll Rect
component doesn't have Movement Type to Elastic, otherwise the component will fuck around the offset adjustment. It should be Unrestricted.