【发布时间】:2020-06-03 18:11:53
【问题描述】:
我在 Unity 中开发一个简单的可滚动 UI。
- 我在场景中有一个画布,它在小时候是空的。
- Empty 是具有不同按钮的长 UI 面板的父项。
我使用以下脚本(分配给 Empty)使其可滚动:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PageSwiper : MonoBehaviour, IDragHandler, IEndDragHandler
{
private Vector3 scrollableUILocation;
// Start is called before the first frame update
void Start()
{
scrollableUILocation = transform.position;
}
public void OnDrag(PointerEventData data)
{
float difference = data.pressPosition.x - data.position.x;
transform.position = scrollableUILocation - new Vector3(difference, 0, 0);
}
public void OnEndDrag(PointerEventData data)
{
scrollableUILocation = transform.position;
}
}
问题是我可以将 UI 面板滚动到屏幕之外。所以我需要让它变得不可能,或者让它如果我滚动得太远,它会顺利返回(到 UI 面板的末尾或开头,取决于哪个更近)
我该怎么做?
我尝试实现以下解决方案,但它不起作用:
我在 UI 面板的左侧和右侧添加了两个 Empty 对象。我试图让我的 UI 面板平滑地移动到其中一个空对象的位置,以防我将它移动到离它们足够近的位置。但它不起作用。
public void OnEndDrag(PointerEventData data)
{
if (Vector3.Distance(transform.position, StartPoint.transform.position) < 1.0f)
{
StartCoroutine(SmoothMove(transform.position, StartPoint.transform.position, easing));
}
else if (Vector3.Distance(transform.position, EndPoint.transform.position) < 1.0f)
{
StartCoroutine(SmoothMove(transform.position, EndPoint.transform.position, easing));
}
}
IEnumerator SmoothMove(Vector3 startpos, Vector3 endpos, float seconds)
{
float t = 0f;
while (t <= 1.0)
{
t += Time.deltaTime / seconds;
transform.position = Vector3.Lerp(startpos, endpos, Mathf.SmoothStep(0f, 1f, t));
yield return null;
}
}
【问题讨论】:
-
您的 OnEndDrag - 两个条件 dnd 例程参数似乎相同
-
@BugFinder 谢谢,已修复。我只用一个“if”语句进行测试,在为这个问题添加第二个语句时忘记更改变量名。
-
您是指运动类型吗?如果不受限制,那么它将滚动到边界之外,如果您将其设置为夹紧或弹性(这是您所描述的),那么它将在容器的末端停止。您还可以启用/禁用垂直/水平滚动,使其仅向一个方向移动
-
@Everts 哇,这是一个很棒的解决方案,我没有使用 ScrollRect,现在将使用它,谢谢!如果您将添加有关 ScrollRect 和 MovementType 的信息作为答案,我会接受!
标签: c# unity3d user-interface