unity滑动窗⼝_Unity实现ScrollView滑动吸附功能
本⽂实例为⼤家分享了Unity实现ScrollView滑动吸附的具体代码,供⼤家参考,具体内容如下
最近在做⼀个展⽰模块的时候遇到了⼀个需要实现滑动窗⼝并且能固定吸附距离的需求,借助UGUI的ScrollView的API以及Dotween实现了这个功能。主要核⼼逻辑就是检测Content节点的RectTransform的localPosX的移动距离然后继承实现OnDrag⼏个接⼝来完成拖动再松开⾃动吸附到具体的位置。具体效果如下
另外说⼀下有⼏个ScrollView⾃带的API需要设置⼀下,⼀个事Movement Type设置成Unrestricted,以及关闭Inertia,这样才能关闭ScrollView⾃带的最⼤距离移动控制不会导致在松⼿吸附过程中因为拖动距离⼤于了左右两边限制⽽最终的移动结束的坐标位置不对。
下⾯贴⼀下代码,脚本直接附在Content物体上既可。
Tip:代码⾥的450 225是⼀个⼦物体宽度的加上content的Space距离,我演⽰的⼯程师⼀个Image420的宽度 30的HorLayout Space,225则是这个距离/2,可以根据具体需求去改变由于只是为了出个DEMO就没有写成变量
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using DG.Tweening;
using DG.Tweening.Core.Easing;
using UnityEngine.Experimental.UIElements;
public class ScorllViewAutoHandler : MonoBehaviour, IEndDragHandler, IBeginDragHandler, IDragHandler
{
private GameObject Scroll;
private ScrollRect sc;
private float OriginPosX;
private float offsetX;
private int CurIndex;
private bool isDragging = false;
private bool TimerFlag = false;
private float Timer;
// Start is called before the first frame update
void Start()
{
CurIndex = 0;
Scroll = this.gameObject;
sc = ansform.parent.gameObject.GetComponent();
}
public void OnEndDrag(PointerEventData eventData)
{
int tempIndex=0;
sc.OnEndDrag(eventData);
offsetX = ansform.localPosition.x - OriginPosX;
if (Mathf.Abs(offsetX) % 450 < 225)
{
tempIndex = (int)(Mathf.Abs(offsetX) / 450);
int _TempTargetIndex = 0;
if (offsetX <0)
{
_TempTargetIndex = CurIndex + tempIndex;
}
else
{
_TempTargetIndex = CurIndex - tempIndex;
}
if (_TempTargetIndex >= 0 && _TempTargetIndex <= ansform.childCount - 1) {
_TempTargetIndex = _TempTargetIndex;
}
else if (_TempTargetIndex < 0)
{
_TempTargetIndex = 0;
}
else
{
_TempTargetIndex = ansform.childCount - 1;
}
Debug.LogError("本次位移⽬标" + _TempTargetIndex + "初始" + CurIndex);
else
{
tempIndex = (int)(Mathf.Abs(offsetX) / 450);
tempIndex += 1;
int _TempTargetIndex = 0;
if (offsetX < 0)
{
_TempTargetIndex = CurIndex + tempIndex;
}
else
{
_TempTargetIndex = CurIndex - tempIndex;
}
if (_TempTargetIndex >= 0 && _TempTargetIndex <= ansform.childCount - 1) {
_TempTargetIndex = _TempTargetIndex;
}
else if (_TempTargetIndex < 0)
{
_TempTargetIndex = 0;
}
else
{
_TempTargetIndex = ansform.childCount - 1;
}
Debug.LogError("本次位移⽬标" + _TempTargetIndex + "初始" + CurIndex);
}
public void OnBeginDrag(PointerEventData eventData)
{
sc.OnBeginDrag(eventData);
OriginPosX = ansform.localPosition.x;
CurIndex = (int)(Mathf.ansform.localPosition.x) / 450);
offsetX = 0;
//当⿏标在A对象按下并开始拖拽时 A对象响应此事件
// 此事件在OnInitializePotentialDrag之后响应 OnDrag之前响应
/
/Debug.Log("OnBeginDrag " );
unity 教程}
public void OnDrag(PointerEventData eventData)
{
sc.OnDrag(eventData);
//Debug.LogError("Dragging" );
}
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持云海天教程。