只能向一个方向滚动

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

我有一个统一的无限垂直滚动条,我想在达到(可变)阈值时突然限制滚动(仅在一个方向上)。

public GameObject MyScrollRectContent;
public float limit = 300;

void Update () {
    if(MyScrollRectContent.transform.localPosition.y >= limit){
        //make it ONLY possible to scroll backwards or not beyond the limit and stop elasticity
    }

任何想法如何限制无限滚动?

unity3d scroll scrollbar vertical-scrolling
1个回答
0
投票

最简单的方法是使用现有的ScrollRect。它允许滚动定义的矩形。你必须通过在一个方向上设置一个非常大的尺寸来模拟无穷大,或者如果用户走得太远就找到一种无缝重置位置的方法(很难看到跳跃但很可能取决于你的内容)。

如果这不是一个可接受的解决方案:

要限制滚动,您可以在用户过高时将位置设置为限制:

void Update () 
{
    if(MyScrollRectContent.transform.localPosition.y >= limit)
    {
        var currentPos = MyScrollRectContent.transform.localPosition;
        MyScrollRectContent.transform.localPosition = new Vector3(currentPos.x, limit, currentPos.z);
    }
}

现在,如果你想要弹性,那就有点棘手了:在某个地方,你的脚本当前必须设置MyScrollRectContent.transform.localPosition。而不是这样做,设置一个targetYPosition。你可以把它想象成一个移动的点,在这个点上,scrollrect由弹性连接。此targetYPosition受限于您的限制。然后在您的更新中,您可以按照ScrollRectContent进行操作。

public void OnUserInput(float y) // I don't know how you actually do this. this is an example
{
    _targetYposition = y;
    if(_targetYposition > limit)
    {
        _targetYPosition = limit;
    }
}

private void Update()
{
    var currentPos = MyScrollRectContent.transform.localPosition;
    var y = 
        Vector3.Lerp(currentPos.y,
                     _targetYPosition, Time.deltaTime*_speed);
    MyScrollRectContent.transform.localPosition = new Vector3(currentPos.x, y, currentPos.z);
}

请注意,这是一个简单的示例,旨在向您暗示正确的方向。您必须使其适应您的代码。弹性可能看起来不像您想要的那样,因此您可能希望修改Update函数以创建其他效果

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