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;
}
}
检测鼠标滚轮控制ScrollView滚动
最新推荐文章于 2024-05-29 08:17:57 发布
该脚本是一个Unity3D中的ScrollView控制器,使用ScrollRect组件并监听鼠标滚轮事件来实现内容滚动。在Update函数中检测鼠标滚轮移动,并在OnScroll方法中处理滚动逻辑,调整content的anchoredPosition以实现视图滚动。当鼠标在UI范围内时,脚本才会响应滚动事件。
摘要由CSDN通过智能技术生成