检测鼠标滚轮控制ScrollView滚动

该脚本是一个Unity3D中的ScrollView控制器,使用ScrollRect组件并监听鼠标滚轮事件来实现内容滚动。在Update函数中检测鼠标滚轮移动,并在OnScroll方法中处理滚动逻辑,调整content的anchoredPosition以实现视图滚动。当鼠标在UI范围内时,脚本才会响应滚动事件。
摘要由CSDN通过智能技术生成
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ScrollViewCtrl : MonoBehaviour
{
    ScrollRect _ScrollRect;
    RectTransform _Content;

    private float _Speed = 35;
    // Start is called before the first frame update
    void Start()
    {
        _ScrollRect = transform.GetComponent<ScrollRect>();
    }

    // Update is called once per frame
    void Update()
    {
        float mouseCenter = Input.GetAxis("Mouse ScrollWheel");

        //Debug.Log("mouseCenter:" + mouseCenter);

        if (mouseCenter == 0)
        {
            return;
        }

        //鼠标是否在ui内
        if (RectTransformUtility.RectangleContainsScreenPoint(transform.GetComponent<RectTransform>(),Input.mousePosition))
        {
            //Debug.Log("在遮挡范围内");
            OnScroll(Input.mouseScrollDelta);
        }        
    }

    /// <summary>
    /// 用Unity源码改写的组件滚动操作
    /// </summary>
    /// <param name="vector2"></param>
    public virtual void OnScroll(Vector2 vector2)
    {
        Vector2 delta = vector2;
        // Down is positive for scroll events, while in UI system up is positive.
        delta.y *= -_Speed;
        if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y))
            delta.y = delta.x;
        delta.x = 0;

        Vector2 position = _ScrollRect.content.anchoredPosition;
        position += delta * _ScrollRect.scrollSensitivity;
        _ScrollRect.content.anchoredPosition = position;

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值