如何为可滚动UI(Unity)设置滚动距离限制?

问题描述 投票:0回答:1

我在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;
    }
}
c# unity3d user-interface
1个回答
0
投票

因此,最好使用ScrollRect,因为它已经包含了此类功能所需的所有操作。

MovementType将定义到达容器末端时系统的反应(根据文档):

  • 无限制的内容可以永远移动。
  • 弹性内容物可以暂时移出容器,但会被弹性拉回。
  • 已夹紧内容不能移出其容器。

考虑到您的按钮系统很长,可能需要动态设置,因此您可以考虑使用ContentSizeFitter。

您添加了滚动视图对象。默认情况下将包括:

  • 滚动视图
  • 视口
  • 内容

现在将Text组件添加到Content对象,而不是text子组件。还要添加一个ContentSizeFitter并将垂直拟合设置为首选大小。这是因为我将处理垂直扩展。

请确保视口占据了应作为遮罩的空间。首先练习,将ScrollView对象放置在中间,并将视口的锚点设置为0.1,这样就需要整个父对象。

[您还可以做更多的事,我建议您研究一下免费的Unity UI extension library,因为它有一些奇特的手风琴或无尽的滚动效果。

© www.soinside.com 2019 - 2024. All rights reserved.