開始位置と終了位置を指定し、二点の間の〇割の位置を取得できるVector3.Lerpの使い方についてです。
始点と終点の確認

この後の話のために、まず始点と終点を決めときます。オブジェクトを置いて、

クリックするとこのオブジェクトを左に10動かす、というスクリプトをアタッチします。

ゲームを動かします。この場合、クリック前の初期位置(a)が始点で、

クリックした後の位置(b)が終点となります。
もう一回このオブジェクトをクリックした場合はさらに左へ進むので、この位置bが始点ということになります。
もう一回このオブジェクトをクリックした場合はさらに左へ進むので、この位置bが始点ということになります。
Vector3.Lerp
始点と終点から指定比率の中間位置を求める
Vector3.Lerp(a, b, t)
※aは始点、bは終点。それぞれVector3で指定する
※tはaとbの間の何割の位置かをfloatで指定する
Vector3.Lerp(a, b, t)
※aは始点、bは終点。それぞれVector3で指定する
※tはaとbの間の何割の位置かをfloatで指定する

Vector3.Lerpを使うと、この始点aと終点bの間の点tを取得することができます。
使い方としては以下のように、transform.positionにVector3.Lerpで求めた座標を代入します。
使い方としては以下のように、transform.positionにVector3.Lerpで求めた座標を代入します。
//Unity C#
void OnMouseDown()
{
//始点
Vector3 a = this.transform.position;
//終点
Vector3 b = this.transform.position;
b.x = b.x - 10f;
//中間点(0.5f=50%の位置)
float t = 0.5f;
//オブジェクトの位置を指定
this.transform.position = Vector3.Lerp(a, b, t);
}

ゲームを実行してクリックすると、視点と終点の中間地点(0.5)にオブジェクトが移動します。

tを0.2fにすれば2割ずつ、

tを0.8fにすれば8割ずつ移動します。
例:なめらかに遅くなる

tを変化させながら何度も処理を繰り返すことで、なめらかに移動させることができます。
下記はループごとに現在地を取得し、目的地点-現在地の2%分ずつ移動させることで、目的地に近づくほどゆっくりと移動するようにした例です。
目的地には理論上永久に到達しないので、ループが終わったら誤差を無視できるほど接近しているものとして、ワープさせています。
下記はループごとに現在地を取得し、目的地点-現在地の2%分ずつ移動させることで、目的地に近づくほどゆっくりと移動するようにした例です。
目的地には理論上永久に到達しないので、ループが終わったら誤差を無視できるほど接近しているものとして、ワープさせています。
式中で使用している待機処理(StartCoroutine、IEnumerator、WaitForSecondsなど)については左記記事参照。
//Unity C#
void OnMouseDown()
{
StartCoroutine("MoveToLeft");
}
IEnumerator MoveToLeft()
{
int i = 0;
//終点
Vector3 b = this.transform.position;
b.x = b.x - 10f;
while (i < 1000)
{
yield return new WaitForSeconds(0.01f);
i++;
//ループごとに現在地を取得
Vector3 a = this.transform.position;
//終点-現在地の2%分移動(永久に目的地にはつかない)
this.transform.position = Vector3.Lerp(a, b, 0.02f);
}
//終点にワープ
this.transform.position = b;
}

やりたいことから逆引きするUNITYの使い方まとめ
Unityをやりたいことから学習していけるよう、機能・用途別にまとめたページです。C#の命令別の逆引きは現時点で作っていません。2019の時期に書き始めているので、それより前のバージョンについては言及しません。
コメント