您的位置:首页 > 移动开发 > Unity3D

Unity两点间的线性插值及其协程的使用

2016-06-05 11:03 295 查看
Unity两点间的线性插值及其协程的使用,我们从代码来分析:

如下是一个执行旋转动作的协程:

        float t0 = transform.eulerAngles.z;
        float t2 = transform.eulerAngles.z + 360;
        float timer = 0;
        while (timer <= time)
        {
            timer += Time.deltaTime;
            float f = Mathf.Lerp(t0, t2, timer/time);
            Debug.Log(timer/time);
            Vector3 rot = Vector3.forward * f;
            transform.eulerAngles = rot;
            yield return null;//此return的作用时,暂停协程,等待下一帧继续运行,使得while循环早多个帧数中执行
        }(这是一个协程,相当于Update(),只是区别在于协程可以通过yield控制程序在特定条件下执行)

//yield return null
不能放在此处是因为,要使物体旋转,必须在多个帧中执行,如果放在此处,就相当于时while循环在一帧中就把while语句执行完成了,达不到动画的效果
其中:float f=Mathf.Lerp(t0,t2,timer/time);其返回的值是由t0到t2之间的值,当timer/time的值为0时,返回值为t0,当timer/time的值为1时,f的值为t2;我们约定Mathf.lerp(t0,t2,t)的参数t的区间为t[0,1]之间;官方代码解析:

Linearly interpolates between 
a
 and 
b
 by 
t
.

The parameter 
t
 is clamped to the range
[0, 1].

When 
t
 = 0 returns 
a


When 
t
 = 1 return 
b


When 
t
 = 0.5 returns the midpoint of 
a
 and 
b
.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
public float minimum = 10.0F;
public float maximum = 20.0F;
void Update() {
transform.position = new Vector3(Mathf.Lerp(minimum, maximum, Time.time), 0, 0);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息