一: 勻速移動,可以到達目標點
Vector3.MoveTowars(從哪,到哪,速度);
例子:
1 Vector3 targetPos = new Vector3(this.transform.position.x, this.transform.position.y, 10); 2 this.transform.position = Vector3.MoveTowards(this.transform.position, targetPos, 0.05f);
效果GIF:
二: 按比例移動,不能到達目標點(無限接近)
Vector3.Lerp(從哪,到哪,速度)
例子:
1 Vector3 targetPos = new Vector3(this.transform.position.x, this.transform.position.y, 10); 2 this.transform.position = Vector3.Lerp(this.transform.position, targetPos, 0.01f);
效果GIF,注意看右上角的position z的值,是9.999無限接近
三: 自然移動(可手動調節的,可快可慢)
起點固定,終點固定,比例根據曲線變化
在Unity界面中可以看到曲線編輯器
雙擊黑色框框,會打開編輯界面
曲線編輯界面
雙擊線上任意位置,即可添加線段,可自由拉伸曲線
例子:
1 public class test : MonoBehaviour 2 { 3 4 public AnimationCurve curve; 5 private float x ; 6 public float Speed = 1f; //---速度 7 8 void Update() 9 { 10 x += Time.deltaTime / Speed; 11 Vector3 targetPos = new Vector3(0, 0, 10); 12 this.transform.position = Vector3.Lerp(Vector3.zero, targetPos, 13 curve.Evaluate(x)); 14 } 15 }
效果GIF: 到達時間,請修改Speed值
自然移動不限制邊界(回彈效果)
方法: Vector3.LerpUnclamped(從哪,到哪,速度)
代碼:
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class test : MonoBehaviour 6 { 7 8 public AnimationCurve curve; 9 private float x ; 10 11 12 void Update() 13 { 14 x += Time.deltaTime; 15 Vector3 targetPos = new Vector3(0, 0, 10); 16 this.transform.position = Vector3.LerpUnclamped(Vector3.zero, targetPos, curve.Evaluate(x)); 17 } 18 }
使用的曲線
效果GIF