How do I create the Zoom-in and Zoom-out feature in Unity-3d using UI button click?
Solution depends on your specific setup, but this should be a good starting point, if you're using an ortographic Camera . If you're using a perspective camera instead, you should move its Transform 's position forward or backwards. I'm also using Mathf.Clamp to restrict the zooming level to a specific range.
using UnityEngine;
using UnityEngine.UI;
public class Zoomer: MonoBehaviour
{
public Button zoomInButton;
public Button zoomOutButton;
public float zoomDelta = 0.1f;
public float minZoom;
public float maxZoom;
Camera cam;
void Start()
{
cam = Camera.main;
}
void OnEnable()
{
zoomInButton.onClick.AddListener(delegate { Zoom(-zoomDelta); });
zoomOutButton.onClick.AddListener(delegate { Zoom(zoomDelta); });
}
void Zoom(float value)
{
float v = Mathf.Clamp(
cam.orthographicSize + value,
minZoom,
maxZoom
);
cam.orthographicSize = v;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.