【遊戲課】技術片段之——球面線性插值(SLERP)

球面線性插值Spherical linear interpolation,通常簡稱Slerp),是四元數的一種線性插值運算,主要用於在兩個表示旋轉的四元數之間平滑差值。(wiki)


cos Ω = p0 ∙ p1

\mathrm{Slerp}(p_0,p_1; t) = \frac{\sin {[(1-t)\Omega}]}{\sin \Omega} p_0 + \frac{\sin [t\Omega]}{\sin \Omega} p_1.

Ω → 0時,退化爲線性插值。

\mathrm{Slerp}(p_0,p_1; t) = (1-t) p_0 + t p_1.\,\!

在Unity中,文檔說明如下

Vector3.Slerp

static Vector3 Slerp(Vector3 fromVector3 to, float t);
Description

Spherically interpolates between two vectors.

Interpolates between from and to by amount t. The difference between this and linear interpolation (aka, "lerp") is that the vectors are treated as directions rather than points in space. The direction of the returned vector is interpolated by the angle and its magnitude is interpolated between the magnitudes of from and to.

t is clamped between [0...1]. See Also: Lerp function.

C#代碼如下

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
    public Transform sunrise;
    public Transform sunset;
    public float journeyTime = 1.0F;
    private float startTime;
    void Start() {
        startTime = Time.time;
    }
    void Update() {
        Vector3 center = (sunrise.position + sunset.position) * 0.5F;
        center -= new Vector3(0, 1, 0);
        Vector3 riseRelCenter = sunrise.position - center;
        Vector3 setRelCenter = sunset.position - center;
        float fracComplete = (Time.time - startTime) / journeyTime;
        transform.position = Vector3.Slerp(riseRelCenter, setRelCenter, fracComplete);
        transform.position += center;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章