同时使用Lerp Position和Slerp Rotation(Unity)

时间:2015-08-25 16:12:03

标签: c# unity3d coroutine lerp

这就是我尝试做的事情,当我点击UI元素时,相机会平滑地旋转(查看目标)并同时移动到目标顶部。

为了执行该操作,我使用两个Coroutine一个用于Lerp Position,另一个用于Slerp Rotation。

问题在于旋转无法正常工作,通常相机应该往下看以查看目标的顶部但不是这样做,它看起来像相机首先看目标,然后移动到目标他的立场。

我希望这是可以理解的;)

这是代码c#

Vector3 LocationProjectForPos = new Vector3(Loc_X, 100, Loc_Z);
Vector3 LocationProjectForRot = new Vector3(Loc_X, Loc_Y, Loc_Z);
Vector3 MainCameraPos = MainCamera.transform.position;

if(!IsCameraMoving & LocationProjectForPos != MainCameraPos)
        {
            StartCoroutine (CoroutineMovePositionCamera(LocationProjectForPos));
            StartCoroutine (CoroutineMoveRotationCamera(LocationProjectForRot));
        }
    }

用Lerp移动相机的位置

public IEnumerator CoroutineMovePositionCamera(Vector3 LocationProject)
{
    float lerpTime = 5f;
    float currentLerpTime = 0f;

    IsCameraMoving = true;

    Vector3 startPos =  MainCamera.transform.localPosition;
    Vector3 endPos =  LocationProject;

    while (lerpTime > 0)
    {
        lerpTime -= Time.deltaTime;
        currentLerpTime += Time.deltaTime;

        if (currentLerpTime > lerpTime) 
        {
            currentLerpTime = lerpTime;
        }

    float t = currentLerpTime / lerpTime;
    t = t*t*t * (t * (6f*t - 15f) + 10f);
    //t = t*t * (3f - 2f*t);
    //t = 1f - Mathf.Cos(t * Mathf.PI * 0.5f);
    MainCamera.transform.localPosition = Vector3.Lerp(startPos, endPos, t);

    yield return null;  
    }
    IsCameraMoving = false;
}

使用Slerp旋转相机

public IEnumerator CoroutineMoveRotationCamera(Vector3 LocationProject)
{
    float lerpTime = 5f;
    float currentLerpTime = 0f;

    IsCameraMoving = true;

    Vector3 relativePos =  LocationProject - MainCamera.transform.localPosition;
    Quaternion rotation = Quaternion.LookRotation(relativePos);
    Quaternion current = MainCamera.transform.localRotation;

    while (lerpTime > 0)
    {
        lerpTime -= Time.deltaTime;
        currentLerpTime += Time.deltaTime;

        if (currentLerpTime > lerpTime) 
        {
            currentLerpTime = lerpTime;
        }

    float t = currentLerpTime / lerpTime;
    t = t*t*t * (t * (6f*t - 15f) + 10f);
    //t = t*t * (3f - 2f*t);
    //t = 1f - Mathf.Cos(t * Mathf.PI * 0.5f);
    MainCamera.transform.localRotation = Quaternion.Slerp(current, rotation, t);

    yield return null;  
    }
    IsCameraMoving = false;
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

CoroutineMoveRotationCamera 中,您需要更新while循环中的 relativePostion rotation

相机移动时相对位置正在改变。现在,您的相机会根据您在while循环开始之前拍摄的矢量快照进行旋转。

在yield语句后添加以下代码。

relativePos = LocationProject - Camera.main.transform.position;
rotation = Quaternion.LookRotation(relativePos);

答案 1 :(得分:0)

在启动协同程序之前,您应该使用成员vars而不是函数local vars保存初始变量