Vector3のLerpを動画にしました。
Lerpをなんとなく使っている人に見ていただけると幸いです。
動画
オブジェクトの色も線形補間(Color.Lerp)によって変化させています。 # Lerp(Vector3 a, Vector3 b, float t) #### 引数 * Vector3 a :開始点 * Vector3 b :終了点 * **float t :二点の補間値**投稿用
— TANUKEINA (@FH1b4mzzirXPoiM) September 13, 2020
Lerpサンプル pic.twitter.com/WrcG27dAld
二点間を線形補間するメソッド。
$y=f(x)$上の二点$(x_1,y_1),(x_2,y_2)$に対して、
y = y_1 + \frac{y_1-y_2}{x_2-x_1}(x-x_1)
で近似を行う。
二点の補間値tは以下の式となる。
t = \frac{x-x_1}{x_2-x_1}
すなわち、$y=f(x)$上の点$(x,y)$が、どのくらい終点に近づいているかを表している。
この辺は以下の記事に大変わかりやすい図が載っています。
LerpExample
LerpExample.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LerpExample : MonoBehaviour
{
//始点
public Transform startMarker;
//終点
public Transform endMarker;
//速度
public float speed = 1.0f;
//ColorLerpクラスのために非表示public
//二点の補間値
[System.NonSerialized]
public float fractionOfJourney;
private float startTime;
private float distance;
private void Start()
{
//動き出した時間
startTime = Time.time;
//二点間の距離
distance = Vector3.Distance(startMarker.position, endMarker.position);
}
private void Update()
{
//移動距離 = 経過時間 * 速度
float distCovered = (Time.time - startTime) * speed;
//移動距離の割合 = 移動距離 / 二点間の距離
fractionOfJourney = distCovered / distance;
//線形補間による移動
transform.position = Vector3.Lerp(startMarker.position, endMarker.position, fractionOfJourney);
}
}
ColorLerp
ColorLerp.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ColorLerp : MonoBehaviour
{
private LerpExample lerpExample;
private Material mat;
private void Start()
{
//LerpExampleから補間値を取得
mat = this.GetComponent<Renderer>().material;
lerpExample = GetComponent<LerpExample>();
}
void Update()
{
//青色→赤色へLerpExampleと同じ補間値で推移
mat.color = Color.Lerp(Color.blue, Color.red, lerpExample.fractionOfJourney);
}
}
まとめ
- Lerpは線形補間をするメソッド。
- 補間を行ってくれるので、これを使用すると動きが滑らかになる。
- 次回はSlerpの記事を書くつもり