[英]Unity, Quaternion.Euler, rotate only around Y axis
我的主要摄像机在现场:
我有这段代码可以平稳地旋转相机:
private IEnumerator SmoothlyRotateCamera()
{
float duration = 0.3f;
Quaternion from = transform.rotation;
Quaternion to = from * Vector3.up * 180f;
float elapsed = 0.0f;
while (elapsed < duration)
{
transform.rotation = Quaternion.Slerp(from, to, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
transform.rotation = to;
isRotating = false;
yield return null;
}
目前,我的相机的旋转角度是[30, -60, 0]
,我希望它绕Y轴旋转180度。
理论上,要实现对Vector3.up * 180f
旋转,一切听起来都不错,但事实上,当我以这种方式旋转时,它也会同时旋转所有其他轴。
如果我通过new Vector3(180f, 0f, 0f)
旋转它-仅X轴会受到影响。
如果我通过new Vector3(0f, 0f, 180f)
旋转它-仅Z轴会受到影响。
如果我通过new Vector3(0f, 180f, 0f)
旋转它,则所有轴也会旋转。
我已经通过将X旋转设置为0来检查了旋转,所以现在我的相机的旋转是[0, -60, 0]
Vector3.up * 180f
[0, -60, 0]
,如果按Vector3.up * 180f
的方式旋转它,那么一切正常精细! 但是,我需要将相机的X留在原处。 例如,在编辑器中仅旋转Y即可得到所需的结果。
我该怎么办? 如何仅通过Y轴旋转180度?
PS:我了解transform.Rotate
但就我而言,我需要使用此处介绍的方式对其进行旋转。
谢谢!
而是使用transform.Rotate
private IEnumerator SmoothlyRotateCamera()
{
var duration = 0.3f;
// in angles per second
var rotationSpeed = 180f / duration;
float rotated = 0;
do
{
var angle = Mathf.Min(180.0f - rotated, rotationSpeed * Time.deltaTime);
var rotation = Vector3.up * angle;
rotated += angle;
// depends which Y axis you want to rotate around here
// pass Space.World to rotate around the global Y axis instead of the local one
// if left out it rotates around its transform.up vector instead
transform.Rotate(rotation, Space.World);
yield return null;
} while (rotated < 180f);
isRotating = false;
// your last yield return is redundant
}
我添加了Mathf.Min
以确保没有超调。 如您所见,它正好在180°上着陆并且在时间上是平滑的(仅使用Time.deltaTime
就不必使用Lerp
了)。
为了显示效果,我仅将持续时间更改为3
而不是0.3
(这很快就可以注意到)。
使用transform.Rotate(rotation, Space.World);
绕全局Y transform.Rotate(rotation, Space.World);
使用transform.Rotate(rotation);
绕局部Y transform.Rotate(rotation);
您可以尝试使用Euler Angles。
transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y + 180, transform.eulerAngles.);
您的代码将变为:
private IEnumerator SmoothlyRotateCamera()
{
float duration = 0.3f;
Vector3 from = transform.eulerAngles;
Vector3 to = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y +180, transform.eulerAngles.z);
float elapsed = 0.0f;
while (elapsed < duration)
{
transform.eulerAngles = Vector3.Slerp(from, to, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
transform.eulerAngles = to;
isRotating = false;
yield return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.