今天面试时碰到了一道面试题,需要完成物体平移的功能。平常项目都是傻傻地直接用Animator实现需求,今天才发现想要实现这种简单地平移的效果,直接用代码就可以了(我真傻,真的(´;︵;`) )被自己蠢死了
Unity - Scripting API: Mathf.MoveTowards
public static float MoveTowards(float current, float target, float maxDelta);
Mathf.MoveTowards方法的功能是返回一个浮点数,其值为current向target靠近的一个值。靠近多少呢?由maxDelta决定。
举个例子:
i = Mathf.MoveTowards(i, 10, 4);
若 i 的初值为0,运行一次 i 的值变为4,再运行一次变为8,再运行一次变为10
Unity - Scripting API: Vector3.MoveTowards
public static Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta);
和Mathf.MoveTowards大同小异,返回的Vector3类型值取于current移向target直线距离的某处。
maxDistanceDelta就是移动的长度。
MoveTowards方法的精髓在于和Update结合使用。
public float yMax = 100;
public float speed = 2f;
void Update()
{
Vector3 v = transform.localPosition;
transform.localPosition = new Vector3(v.x, Mathf.MoveTowards(v.y, yMax, speed), v.z);
}
运行脚本,物体就会延着y轴平移,直到它在y轴方向的值达到yMax。speed越大,移动速度越快。
当然也可以speed * Time.deltaTime,可以无视帧率来决定移动速度。
Vector3.MoveTowards的写法也是大同小异:
public Vector3 vector3 = new Vector3(100, 100, 100);
public float speed = 2f;
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, vector3, speed);
}
运行脚本,物体平移至vector3位置
MoveTowards方法也可以和协程结合使用。
private IEnumerator IEMoveFillAmount(Image image, float speed)
{
while (image.fillAmount < 1)
{
image.fillAmount = Mathf.MoveTowards(image.fillAmount, 1, speed / 100);
yield return new WaitForSeconds(0.01f);
}
}
上述代码的功能是使Image的fillAmount按每0.01秒增加speed / 100的速度增大,直到image.fillAmount大于等于1
如果不想让物体做匀速运动,可以巧妙地运用Lerp方法,使物体做匀加速运动
Unity - Scripting API: Mathf.Lerp
public static float Lerp(float a, float b, float t);
Unity - Scripting API: Vector3.Lerp
public static Vector3 Lerp(Vector3 a, Vector3 b, float t);
不过这就是其他的内容了,这里只给个思路
喜欢的话,可以点赞呦~