Unity Lerp 선형보간

조회수 921회

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

public class TitanAttack : MonoBehaviour {

public GameObject player;
public GameObject titan;
public GameObject Rhand;
public GameObject Lhand;

private Vector3 position;
private Vector3 Rhandpos;

public float speed;

void smash()
{
    Vector3 pos = new Vector3(position.x, 10, position.z);
    Rhand.transform.position = Vector3.Lerp(Rhandpos, pos, Time.deltaTime * speed);
}

void swing()
{

}

void attack()
{
    position = player.transform.position;
    if (Vector3.Distance(position, titan.transform.position) > 26)
    {
        smash();
    }
    else
    {
        swing();
    }
}

// Use this for initialization
void Start () {
    Rhandpos = new Vector3(-15, 5, 35);
    InvokeRepeating("attack", 3, 10);
}

// Update is called once per frame
void Update () {

}

}

제가 만든 위의 smash 코드에서 Lerp를 실행하다가 말고 중간에 멈춰버리는데 어떻게 해야 끝까지 갈까요?

1 답변

  • Time.deltaTime은 매 프래임당 걸린 시간이 리턴되므로 이걸 사용하는 경우는 현재를 기준으로 delta 계산을 할 때 입니다. 이 값으로 구현하시려면 매 delta를 누적하는 상태 변수를 따로 두어야 합니다.

    보간으로 애니메이션 혹은 위치 값을 지정해야 하는 경우, 보통은 시작 시간을 기준으로 현재 시간과의 차이값을 사용합니다.


    Lerp 함수의 세 번째 파라메터는 0 ~ 1.0 사이의 값이 와야 합니다.

    세번째 파라메터로 들어가는 값은 무엇을 기준으로 하느냐에 따라 달라집니다.

    총 거리를 기준으로 한다면

    https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html 이 예제의 update() 함수를 보시면 되고

    총 걸리는 시간을 기준으로 한다면

    float ratio = (startTime - Time.time) / totalTime;
    Rhand.transform.position = Vector3.Lerp(Rhandpos, pos, ratio);
    
    • 여기서 혹시 totalTime은 무엇을 의미하는 것인가요? 김태랑 2018.10.25 19:48
    • 그리고 위의 코드같은 경우에 startTime을 어떤 함수 내에서 받아야 하는지도 알려주세요. 김태랑 2018.10.25 19:49
    • 일단은 총 걸리는 시간을 기준으로 해보려고 합니다 김태랑 2018.10.25 19:49
    • 구조 자체는 링크의 예제와 비슷합니다. smash()에서 startTime = Time.time으로 받고 update마다(매프레임마다) startTime - Time.time으로 위치를 변경시켜줘야 합니다. Update함수는 매 프레임 콜 될테니 특정 플래그를 두고 [smash()에서 플래그 set] => [update() 내에서는 flag:set 일경우에 애니메이션 수행, 조건문으로 deltaTime이 totalTime을 넘어가면 unset] 하는 로직이 필요하겠죠. doodoji 2018.10.25 20:00

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)