본문 바로가기
개발/Unity

Unity) ScrollRect TargetScroll (특정 아이템을 기준으로 스크롤 이동)

by 테샤르 2023. 4. 27.

ScrollRect TargetScroll (특정 아이템을 기준으로 스크롤 이동)

Scroll의 위치를 계산해야하는 경우에 유용한 코드이다.

Scroll의 전체 크기를 World 좌표를 통해서 해당 값과 Mask Rect(ViewPort)를 계산을 해서 

Scroll의 normalizedPosition을 변경해서 Center 를 기준으로 계산이된다.

 

 

해당코드를 사용하면

원하는 Scroll의 하위에 있는 Content Item을 기준으로 Scroll을 처리할수 있다.

 

using UnityEngine;
using UnityEngine.UI;
 
[RequireComponent(typeof(ScrollRect))]
public class ScrollRectEnsureVisible : MonoBehaviour
{
    public RectTransform maskTransform;
 
    private ScrollRect mScrollRect;
    private RectTransform mScrollTransform;
    private RectTransform mContent;
 
    public void CenterOnItem(RectTransform target)
    {
        // Item is here
        var itemCenterPositionInScroll = GetWorldPointInWidget(mScrollTransform, GetWidgetWorldPoint(target));
        // But must be here
        var targetPositionInScroll = GetWorldPointInWidget(mScrollTransform, GetWidgetWorldPoint(maskTransform));
        // So it has to move this distance
        var difference = targetPositionInScroll - itemCenterPositionInScroll;
        difference.z = 0f;
 
        //clear axis data that is not enabled in the scrollrect
        if (!mScrollRect.horizontal)
        {
            difference.x = 0f;
        }
        if (!mScrollRect.vertical)
        {
            difference.y = 0f;
        }
 
        var normalizedDifference = new Vector2(
            difference.x / (mContent.rect.size.x - mScrollTransform.rect.size.x),
            difference.y / (mContent.rect.size.y - mScrollTransform.rect.size.y));
 
        var newNormalizedPosition = mScrollRect.normalizedPosition - normalizedDifference;
        if (mScrollRect.movementType != ScrollRect.MovementType.Unrestricted)
        {
            newNormalizedPosition.x = Mathf.Clamp01(newNormalizedPosition.x);
            newNormalizedPosition.y = Mathf.Clamp01(newNormalizedPosition.y);
        }
 
        mScrollRect.normalizedPosition = newNormalizedPosition;
    }
    private void Awake()
    {
        mScrollRect = GetComponent<ScrollRect>();
        mScrollTransform = mScrollRect.transform as RectTransform;
        mContent = mScrollRect.content;
        Reset();
    }
    private void Reset()
    {
        if (maskTransform == null)
        {
            var mask = GetComponentInChildren<Mask>(true);
            if (mask)
            {
                maskTransform = mask.rectTransform;
            }
            if (maskTransform == null)
            {
                var mask2D = GetComponentInChildren<RectMask2D>(true);
                if (mask2D)
                {
                    maskTransform = mask2D.rectTransform;
                }
            }
        }
    }
    private Vector3 GetWidgetWorldPoint(RectTransform target)
    {
        //pivot position + item size has to be included
        var pivotOffset = new Vector3(
            (0.5f - target.pivot.x) * target.rect.size.x,
            (0.5f - target.pivot.y) * target.rect.size.y,
            0f);
        var localPosition = target.localPosition + pivotOffset;
        return target.parent.TransformPoint(localPosition);
    }
    private Vector3 GetWorldPointInWidget(RectTransform target, Vector3 worldPoint)
    {
        return target.InverseTransformPoint(worldPoint);
    }
}

 

반응형

 

원본 Unity Community : [링크]

 

ScrollRect scroll to a gameObject position ?

Hello, I would like to know how to move my scroll rect vertically to another gameobject. Here is an example : [IMG] I have already tried to move it...

forum.unity.com

 

 

Unity Scroll Rect : [링크]

 

스크롤 사각 영역 - Unity 매뉴얼

공간을 많이 차지하는 콘텐츠를 작은 영역에 표시해야 할 때 스크롤 사각 영역을 활용할 수 있습니다. 스크롤 사각 영역(Scroll Rect)은 콘텐츠를 스크롤하는 기능을 제공합니다.

docs.unity3d.com

 

★☆☆☆☆

 

반응형

댓글