Overview: Keeping Track of Time 记录时间

The Time class contains a very important class variable called deltaTime. This variable contains the amount of time since the last call to Update or FixedUpdate (depending on whether you are inside an Update or a FixedUpdate function).

So the previous example, modified to make the object rotate with a constant speed not dependent on the frame rate becomes:

Time 类包含一个非常重要的变量叫deltaTime.这个变量包含从上次调用Update 或FixedUpdate到现在的时间(根据你是放在Update函数还是FixedUpdate函数中).(另注: Update每帧调用一次)

依照上面的例子,使物体在一个均匀的速度下旋转,不依赖帧的频率,如下:

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Update() {
        transform.Rotate(0, 5 * Time.deltaTime, 0);
    }
}
function Update() {
    transform.Rotate(0, 5 * Time.deltaTime, 0);
}

Moving the object: 移动物体:

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Update() {
        transform.Translate(0, 0, 2 * Time.deltaTime);
    }
}
function Update() {
    transform.Translate(0, 0, 2 * Time.deltaTime);
}

If you add or subtract to a value every frame chances are you should multiply with Time.deltaTime. When you multiply with Time.deltaTime you essentially express: I want to move this object 10 meters per second instead of 10 meters per frame. This is not only good because your game will run the same independent of the frame rate but also because the units used for the motion are easy to understand. (10 meters per second)

Another example, if you want to increase the range of a light over time. The following expresses, change the radius by 2 units per second.

如果你每帧添加或减少一个值,你需要乘以 Time.deltaTime .在你乘以 Time.deltaTime 的同时你必须明确:你是以每秒10米而不是每帧10米来移动物体.这样你的游戏就会以自己的节奏来运行而不是依赖帧的频率,因而也使游戏中的运动更容易掌握.(每秒10米)

另外一个例子,如果你想要每隔一段时间增加光照范围.下面的代码实现的是每秒增加半径2个单位.

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Update() {
        light.range += 2.0F * Time.deltaTime;
    }
}
function Update() {
    light.range += 2.0 * Time.deltaTime;
}

When dealing with rigidbodies through forces, you generally don't multiply by Time.deltaTime since the engine already takes care of that for you.

当涉及到作用于刚体的力时,通常不乘以 Time.deltaTime .因为引擎已经为你处理了.

最后修改:2010年11月30日 Tuesday 22:54

本脚本参考基于Unity 3.4.1f5

英文部分版权属©Unity公司所有,中文部分© Unity圣典 版权所有,未经许可,严禁转载 。