유니티

[유니티]Lerp , SmoothDamp

seyeol 2023. 3. 1. 22:44
반응형

https://www.youtube.com/watch?v=_QOvSLCXm7A&t=331s

오늘 코딩님의 Lerp관련 영상을 보고서 원래 가지고 있던 궁금증이 풀리게 되었다

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LerpSmoothDamp : MonoBehaviour
{
    public Transform EndPos;

    // Update is called once per frame
    void Update()
    {
        transform.position = Vector3.Lerp(transform.position, EndPos.position, 10 * Time.deltaTime);
    }
}

 

 

위 코드 처럼 Lerp를 항상 잘못된 방식으로 써와서 오브젝트가 목표 지점에 가까워 질때 느려지는 SmoothDamp와 비슷한 이동을 보여서 왜 두개의 함수가 존재하나 싶었는데 잘못된 방식으로 써오고 있었다

transform.position = Vector3.Lerp(StartPos.postion, EndPos.position, Number);

위의 변수는 임의로 정하였다

Lerp는 StartPos의 위치와 EndPos의 위치간의 거리간격을 1로 설정하고 0부터 1까지 이동하는인데 여기에 Number 값에 해당하는 위치로  이동하는 방식으로 쓰는것이였다

transform.position = Vector3.Lerp(transform.position, EndPos.position, 10 * Time.deltaTime);

원래 내가 평소에 쓰던 방식으로 썼다면 시작 위치인 StartPos의 위치가 바뀌기 때문에 시작 위치와 끝나는 위치간의 거리차이가 점점 줄어들기 때문에 원래의 Lerp의 기능을 활용하지 못하고 있었다 

public class LerpSmoothDamp : MonoBehaviour
{
    public Transform EndPos;
    public Transform StartPos;
    public float curTime;
    public float lerpTime;
    // Update is called once per frame
    void Update()
    {
        curTime += Time.deltaTime;
        if (curTime >= lerpTime)
        {
            curTime = lerpTime;
        }
       

        transform.position = Vector3.Lerp(StartPos.position, EndPos.position,curTime/lerpTime );
    }
}

이런식으로 시작위치가 유동적이지 않고 고정값이 된다면 밑의 영상처럼 원래 lerpTime의 수치를 조절 하여 시작 위치에서 도착위치까지 도달하는 시간 동안 이동할수있게 만드는 속력으로 이동을 시켜준다 

이제는 진짜 Lerp의 용도를 알았으니 도착지점에 가까워지면 속력이 줄어드는 SmoothDamp에 대해서 알아 보겠다

 

[SmoothDamp]

왜 언제 사용하나 

밑의 영상 처럼 목표지점으로 이동하는데 목표지점에 가까워질수록 속력이 줄어드는 상황을 연출 할때 사용하는것 같다

 

 

Current는 움직일 오브젝트의 위치

Target은 도착위치

CurrentVelocity는 현재 오브젝트의 속력값

SmoothTime 오브젝트가 Target의 위치까지의 대략의 도착 시간 

MaxSpeed는 오브젝트의 최대 속력

DeltaTime은 SmoothDamp가 마지막의로 호출된 함수이후의 시간을 float 변수에 시간을 더해주는것

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SmoothDamp : MonoBehaviour
{
    // Start is caled before the first frame update
    public Transform Target;
    public Vector3 Velociy;
    public float LastTime;
    // Update is called once per frame
    void Update()
    {
        transform.position = Vector3.SmoothDamp(transform.position, Target.position, ref Velociy, 0.5f, 10,LastTime);
    }
}