[Unity] Rect Transform / Rolling number text yu(슬롯머신 스타일 텍스트 애니메이션) - RectMask2D 이용 / Lerp

PosX PosY PosZ Width Height : 사각형 위치와 크기
Anchor (Min, Max): 부모의 위치 비율
Pivot: 자신의 중심점 비율 (회전할때 중심)

Anchor Preset: 주로 사용되는 앵커 모음
Shift + 클릭시 피봇 (중심점) 변경

부모의 크기만큼 stretch 할 수 있다
Alt + 클릭시 위치 변경
정렬: 수평 / 수직으로 양끝단 / 가운데 정렬
*Pivot 변경시

슬롯형식으로 넘어가는 모양의 텍스트를 구현해보자

(이미지의 Count 부분)
Rectmask2D를 사용해 보여질 구간을 마스크로 정해주고, 텍스트를 2개로 만든 후 위아래로 붙여놓고, 위에 텍스트를 기본텍스트, 아래 텍스트를 변경될 텍스트로 설정한 뒤 두 텍스트를 위로 올려주면 된다. 그 이후 올라간 텍스트는 다시 아래로 내려주면 된다.

Hierarchy창을 보면 이렇게 되면 된다
부모로 있는 GameObject에 RectMask를 넣어주자
그다음 원하는 위치의 스크립트에 코드를 써주자
//변수 선언
public RectTransform text1;
public RectTransform text2;
public TextMeshProUGUI text1Comp;
public TextMeshProUGUI text2Comp;
public float rollDuration = 0.3f;
private float height;
private Coroutine currentRoutine;
//돌리는 함수
public void RollTo(int current, int next)
{
if (currentRoutine != null)
{
StopCoroutine(currentRoutine);
}
currentRoutine = StartCoroutine(RollRoutine(current, next));
}
IEnumerator RollRoutine(int current, int next)
{
text1Comp.text = current.ToString();
text2Comp.text = next.ToString();
text1.anchoredPosition = Vector2.zero;
text2.anchoredPosition = new Vector2(0, -height);
float time = 0f;
while (time < rollDuration)
{
time += Time.deltaTime;
float t = Mathf.Clamp01(time / rollDuration);
float eased = EaseInOutCubic(t);
float y1 = Mathf.Lerp(0, height, eased);
float y2 = Mathf.Lerp(-height, 0, eased);
text1.anchoredPosition = new Vector2(0, y1);
text2.anchoredPosition = new Vector2(0, y2);
yield return null;
}
text1Comp.text = next.ToString();
text1.anchoredPosition = Vector2.zero;
text2.anchoredPosition = new Vector2(0, -height);
currentRoutine = null;
}
RollTo 함수를 원하는 곳에 사용하면 쓸 수 있다.
RollRoutine에서는 두 텍스트의 위치를 바로 잡고, height 값반큼 올라가게 만든다
while문을 돌며 ahcoredPosition으로 매 프레임 이동시키고, 이동이 끝나면 text1에 새 숫자를 복사하고 다시 처음 상태로 초기화한다.
private float EaseInOutCubic(float t)
{
return t < 0.5f
? 4 * t * t * t
: 1 - Mathf.Pow(-2 * t + 2, 3) / 2;
}
EaseInOutCubic: 부드러운 애니메이션 가속/감속을 위한 이징 함수(Easing Function)
t값을 0에서 1로 바꿀때 처음엔 느리게 시작해 중간엔 빨라지고 마지막에는 다시 느려지게 만드는 함수
t<0.5일때 느리게 시작하다가 점점 빠르게 (4*t^3)
t>=0.5일때 빠르게 가다가 점점 느려지게 (1-((-2t+2)^3)/2
나도 처음 봤다

Lerp: a와 b의 값을 혼합
v는 혼합 비율