Unity 鼠标控制 UI 放大、缩小、拖拽

文章目录

  • 1. 代码
  • 2. 测试场景

1. 代码

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class UIDragZoom : MonoBehaviour, IDragHandler, IScrollHandler
{
    private Vector2 originalSize;
    private Vector2 originalPosition;
    private RectTransform rectTransform;
    private float minSize = 30f;
    private float maxSize = 200f;

    private void Start()
    {
        rectTransform = GetComponent<RectTransform>();
        originalSize = rectTransform.sizeDelta;
        originalPosition = rectTransform.anchoredPosition;
    }

    public void OnDrag(PointerEventData eventData)
    {
        rectTransform.anchoredPosition += eventData.delta;
    }

    public void OnScroll(PointerEventData eventData)
    {
        float scroll = eventData.scrollDelta.y;
        Vector2 newSize = rectTransform.sizeDelta + Vector2.one * scroll;
        float temp = Mathf.Clamp(newSize.x, minSize, maxSize);
        newSize = new Vector2(temp, temp);
        rectTransform.sizeDelta = newSize;
    }

    public void ResetUI()
    {
        rectTransform.sizeDelta = originalSize;
        rectTransform.anchoredPosition = originalPosition;
    }
}

2. 测试场景

Unity 鼠标控制 UI 放大、缩小、拖拽_第1张图片

你可能感兴趣的:(Unity,学习笔记,unity,ui,游戏引擎)