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 : [링크]
Unity Scroll Rect : [링크]
★☆☆☆☆
반응형
'개발 > Unity' 카테고리의 다른 글
Unity)Unity 내장 DLL 경로 (0) | 2023.05.03 |
---|---|
Unity)PackageManager) Editor Coroutines(에디터 코루틴) (0) | 2023.05.02 |
Unity) Unity Ads 용어집 (0) | 2023.04.19 |
Unity) 유니티 어필리에이트(Unity Affiliates) (0) | 2023.04.12 |
Unity)C#) 코드 스타일 가이드 만들기 (2) | 2023.04.03 |
댓글