C# 如何不停地平滑旋转对象?
这是我现在使用的脚本:C# 如何不停地平滑旋转对象?,c#,unity3d,rotation,unity5,C#,Unity3d,Rotation,Unity5,这是我现在使用的脚本: 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
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);
}
}
}
它在旋转物体,但问题是无论我在运行游戏时设置什么时间,旋转速度都是相同的。我尝试过:返回新的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
,它返回自上一帧以来经过的时间
看起来是这样的:
public class SpinObject : MonoBehaviour {
float rotationMultiplier = 1.0f;
void Update () {
transform.Rotate(Vector3.forward, Time.deltaTime * rotationMultiplier);
}
}
这将导致对象每秒旋转1度*rotationMultiplier
将rotationMultiplier
增加到10.0f
可以实现每秒平滑10度
编辑-
我想添加Unity关于Time.deltaTime
当你与时间相乘时,你基本上表达了:我想要
将此对象每秒移动10[度]而不是每秒移动10[度]
框架
使用
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
,它返回自上一帧以来经过的时间
看起来是这样的:
public class SpinObject : MonoBehaviour {
float rotationMultiplier = 1.0f;
void Update () {
transform.Rotate(Vector3.forward, Time.deltaTime * rotationMultiplier);
}
}
这将导致对象每秒旋转1度*rotationMultiplier
将rotationMultiplier
增加到10.0f
可以实现每秒平滑10度
编辑-
我想添加Unity关于Time.deltaTime
当你与时间相乘时,你基本上表达了:我想要
将此对象每秒移动10[度]而不是每秒移动10[度]
框架