[Unity]Vector3.lerp和Vector3.Slerp

2019/10 09 21:10

对于方向向量,使用Vector3.lerp是不行的,比如对一个dir和-dir进行插值,是无效的;正确的方式是使用Vector3.Slerp

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

public class LerpTestProj : MonoBehaviour
{
    const int section = 50;
    void OnDrawGizmos()
    {
        DrawSample(Vector3.forward, Vector3.left, 1.0f, 0.0f);
        DrawSample(Vector3.forward, Vector3.back, 1.0f, -3.0f);
    }

    private static void DrawSample(Vector3 dir0, Vector3 dir1, float x, float z)
    {
        Vector3 p0 = new Vector3(-x, 0, z);
        Gizmos.color = Color.red;
        Gizmos.DrawSphere(p0, 0.1f);
        for (int i = 0; i <= section; ++i)
        {
            float t = i / (float)section;
            Vector3 dir = Vector3.Lerp(dir0, dir1, t);
            Gizmos.DrawLine(p0, p0 + dir);
        }

        Vector3 p1 = new Vector3(x, 0, z);
        Gizmos.color = Color.green;
        Gizmos.DrawSphere(p1, 0.1f);
        for (int i = 0; i <= section; ++i)
        {
            float t = i / (float)section;
            Vector3 dir = Vector3.Slerp(dir0, dir1, t);
            Gizmos.DrawLine(p1, p1 + dir);
        }
    }
}