如何防止Scroll Rect在Unity中摇晃?

时间:2018-11-05 11:05:06

标签: c# unity3d scroll lerp

我只希望将面板的尺寸缩小一半。

Like this...

canvas and scroll rect setup

在拖动事件期间,它起作用。面板不能超出预期的一半大小。

但是每当我快速拖动和放下面板时,面板就会不断晃动,看上去会滑动。

if (scroll.anchoredPosition.x >= screenWidthHalf) {
                scroll.anchoredPosition = new Vector2(screenWidthHalf, scroll.anchoredPosition.y);
            }

即使x位置大于screenWidthHalf,if语句也永远不会发生。

完整代码。

private int screenWidthHalf;
public RectTransform scroll;
private bool dragging;
float newX;

// Use this for initialization
void Start () {
    screenWidthHalf = Screen.width / 2;

    scroll.anchoredPosition = new Vector2(scroll.rect.width / 2, scroll.anchoredPosition.y);
}

我认为lerp函数会导致这种情况,并在没有它的情况下进行了尝试,但这没有用。

void Update () {
        if (!dragging) {


            if (scroll.anchoredPosition.x > 0) {
                newX = Mathf.Lerp(scroll.anchoredPosition.x, screenWidthHalf, Time.deltaTime * 5f);
                scroll.anchoredPosition = new Vector2(newX, scroll.anchoredPosition.y);
            }
            if((screenWidthHalf - newX)< 0.1f){scroll.anchoredPosition = new Vector2(screenWidthHalf, scroll.anchoredPosition.y);}



            if (scroll.anchoredPosition.x >= screenWidthHalf) {
                scroll.anchoredPosition = new Vector2(screenWidthHalf, scroll.anchoredPosition.y);
            }


            if (scroll.anchoredPosition.x < 0) {
                newX = Mathf.Lerp(scroll.anchoredPosition.x, -screenWidthHalf, Time.deltaTime * 5f);
                scroll.anchoredPosition = new Vector2(newX, scroll.anchoredPosition.y);
            }
            if ((screenWidthHalf + newX) < 0.1f) {scroll.anchoredPosition = new Vector2(-screenWidthHalf, scroll.anchoredPosition.y);}

        }


        if (scroll.anchoredPosition.x > screenWidthHalf) { scroll.anchoredPosition = new Vector2(screenWidthHalf, scroll.anchoredPosition.y); }
        if (scroll.anchoredPosition.x < -screenWidthHalf) { scroll.anchoredPosition = new Vector2(-screenWidthHalf, scroll.anchoredPosition.y); }

    }

每当我拖动滚动条时,这就是拖动事件

public void StartDrag() { dragging = true; }
public void EndDrag() { dragging = false; }

谢谢。

0 个答案:

没有答案