我怎样才能不停地旋转物体?
How can i rotate object smooth without stop?
这是我现在使用的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpinObject : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
StartCoroutine(ContinuousRotation());
}
IEnumerator ContinuousRotation()
{
while (true)
{
transform.Rotate(Vector3.forward, 10);
yield return new WaitForSeconds(5f);
}
}
}
它正在旋转物体,但问题是无论我设置什么时间,运行游戏的旋转速度都是一样的。我试过: yield return new WaitForSeconds(1f);然后 5f 在原来是 0.01f 但速度永远不会改变。
第二个问题是旋转使物体有些闪烁不是闪烁而是对眼睛的一些干扰它并不是真正旋转平滑。也许问题是速度?
与其跳来跳去延迟事件,不如使用 Time.time
或 Time.deltaTime
例如:
public class SpinObject : MonoBehaviour {
float timeSinceLastRotation;
float timeUntilNextRotation = 0.01f; // 0.01 seconds
void Update () {
if (timeSinceLastRotation + timeUntilNextRotation > Time.time) {
transform.Rotate(Vector3.forward, 10);
timeSinceLastRotation = Time.time
}
}
}
但是,这不是处理平滑旋转的理想方式,因为这会导致对象每 0.01 秒捕捉到下一个 10 度。相反,您应该使用 Time.deltaTime
,其中 returns 自上一帧以来经过的时间。
看起来像这样:
public class SpinObject : MonoBehaviour {
float rotationMultiplier = 1.0f;
void Update () {
transform.Rotate(Vector3.forward, Time.deltaTime * rotationMultiplier);
}
}
这会导致对象旋转1 degree per second * rotationMultiplier
增加rotationMultiplier
到10.0f
可以实现每秒10度的平滑。
编辑-
我想从 Unity Scripting API 添加关于 Time.deltaTime
的修改摘录
When you multiply with Time.deltaTime you essentially express: I want
to move this object 10 [degrees] per second instead of 10 [degrees] per
frame.
这是我现在使用的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpinObject : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
StartCoroutine(ContinuousRotation());
}
IEnumerator ContinuousRotation()
{
while (true)
{
transform.Rotate(Vector3.forward, 10);
yield return new WaitForSeconds(5f);
}
}
}
它正在旋转物体,但问题是无论我设置什么时间,运行游戏的旋转速度都是一样的。我试过: yield return new WaitForSeconds(1f);然后 5f 在原来是 0.01f 但速度永远不会改变。
第二个问题是旋转使物体有些闪烁不是闪烁而是对眼睛的一些干扰它并不是真正旋转平滑。也许问题是速度?
与其跳来跳去延迟事件,不如使用 Time.time
或 Time.deltaTime
例如:
public class SpinObject : MonoBehaviour {
float timeSinceLastRotation;
float timeUntilNextRotation = 0.01f; // 0.01 seconds
void Update () {
if (timeSinceLastRotation + timeUntilNextRotation > Time.time) {
transform.Rotate(Vector3.forward, 10);
timeSinceLastRotation = Time.time
}
}
}
但是,这不是处理平滑旋转的理想方式,因为这会导致对象每 0.01 秒捕捉到下一个 10 度。相反,您应该使用 Time.deltaTime
,其中 returns 自上一帧以来经过的时间。
看起来像这样:
public class SpinObject : MonoBehaviour {
float rotationMultiplier = 1.0f;
void Update () {
transform.Rotate(Vector3.forward, Time.deltaTime * rotationMultiplier);
}
}
这会导致对象旋转1 degree per second * rotationMultiplier
增加rotationMultiplier
到10.0f
可以实现每秒10度的平滑。
编辑-
我想从 Unity Scripting API 添加关于 Time.deltaTime
When you multiply with Time.deltaTime you essentially express: I want to move this object 10 [degrees] per second instead of 10 [degrees] per frame.