c# - Quaternion.Slerp 由于某种原因旋转不顺畅
问题描述
我正在尝试用 Unity 使像物体一样的摇摆不定的物体旋转,并且由于某种原因,旋转是即时的,而不是逐渐的运动。我之前曾研究过 Slerp 和 Lerp,但我无法让它与任何一个一起工作。我想知道是否有人有任何见解,因为我确定我错过了一些愚蠢而简单的 xD。谢谢!这是方法。
private void Rotate(float rotateAmount)
{
var oldRotation = transform.rotation;
transform.Rotate(0, 0, rotateAmount);
var newRotation = transform.rotation;
for (float t = 0; t <= 1.0; t += Time.deltaTime)
{
transform.rotation = Quaternion.Slerp(oldRotation, newRotation, t);
}
transform.rotation = newRotation;
}
}
解决方案
循环中完成的所有旋转for
都发生在一帧下。您看不到它们在一帧下的变化。使该Rotate
函数成为协程函数,然后在每个循环中等待一帧,yield return null
您应该会看到随时间的变化。
private IEnumerator Rotate(float rotateAmount)
{
var oldRotation = transform.rotation;
transform.Rotate(0, 0, rotateAmount);
var newRotation = transform.rotation;
for (float t = 0; t <= 1.0; t += Time.deltaTime)
{
transform.rotation = Quaternion.Slerp(oldRotation, newRotation, t);
yield return null;
}
transform.rotation = newRotation;
}
因为它是一个协程函数,所以你启动它而不是直接调用它:
StartCoroutine(Rotate(90f));
我注意到你曾经transform.Rotate(0, 0, rotateAmount)
得到目标角度。你不需要这样做。如果您需要将对象从当前角度旋转到另一个角度,请获取当前角度,然后将其添加到目标角度并用于Vector3.Lerp
lerp 旋转。
请参阅这篇文章中的“随时间推移的增量角旋转:”部分。
推荐阅读
- python - 为视频处理设置数据管道
- angular - Angular - 使用 PrimeNg 表进行 Jasmine 测试 - 无法验证单元测试中的行数
- r - 更改修改后的 ggpairs 图的轴标签(相关热图)
- c# - C# Windows10 - 仅向 1 个特定用户和管理员授予目录访问权限?
- reactjs - React onClick TypeError:无法读取未定义的属性“值”
- sonarqube - Sonaqube 抛出 java.lang.IllegalArgumentException:主机名可能不为空
- c - 这个输入有什么问题?我在这个程序中遇到分段错误(核心转储)
- javascript - makeStyles 的 Material-UI 问题
- amazon-web-services - 如何使用 AWS CLI 从 EBS 快照创建 AMI
- python - 当我对它进行 dckerize 时,Python3 os.popen 不能与 Nmap 一起使用