![](/img/trans.png)
[英]Why when rotating the object on z axis it's rotating also the x and y and not setting z to 0?
[英]When rotating an object in Unity, the script doesn't rotate the object on the Z-axis, only the X and Y?
我有一个矩形立方体,需要放置在其他两个对象之间,并且它可以正确旋转,使每一端都面向两个对象。 由于这发生在球形世界上,因此问题在于我尝试将其对齐以正确面向“向上”。 我以前没有意识到这一点,但是这段代码(它适用于其他对象,因为它们只需要定向一次)只使用 X 和 Y 轴。 我可以通过在编辑器中修改 Z 轴来手动正确定位它们,所以我知道这是可能的,但由于它们必须按程序创建,这显然是不可行的。 从 transform.up 更改为 down 或 right 完全没有任何变化。
在下面的代码中, parent 是它必须指向的对象之一(它很好),而 target 是球体的中心。
理论上,alignment到两个侧面对象应该只需要使用X和Y轴,而alignment到球心则只需要使用Z轴,如最后一行代码所示,但实际上这不起作用,因为两个对齐都只想使用 X 和 Y 轴而忽略 Z 轴。
Vector3 parentDirection = parent.transform.position - transform.position;
Vector3 targetDirection = target.position - transform.position;
Vector3 DirectionToParent = Vector3.RotateTowards(transform.forward, parentDirection, 100f, 0.0f);
Vector3 CenterDiretion = Vector3.RotateTowards(transform.forward, targetDirection, 100f, 0.0f);
Quaternion ParentRotation = Quaternion.LookRotation(DirectionToParent );
Quaternion CenterRotation = Quaternion.LookRotation(CenterDiretion );
transform.rotation = Quaternion.Euler(DirectionToParent.eulerAngles.x, DirectionToParent.eulerAngles.y, newRotation.eulerAngles.z);
问题中显示的代码不起作用,因为它在计算transform.rotation
时没有考虑到/远离行星中心的方向。
相反,我建议只使用Quaternion.LookRotation
来分配旋转,该旋转将产生您使用 parentDirection 的正向,以及最接近行星向上方向的向上。
Vector3 upDirection = transform.position - target.position;
transform.rotation = Quaternion.LookRotation(parentDirection, upDirection);
如果您需要根据某个最大速度更改旋转,只需将Quaternion.LookRotation
的结果分配给一个变量,并将Quaternion.RotateTowards
从transform.rotation
分配给transform.rotation,并根据需要将结果分配给transform.rotation
:
private float turnVelocity = 100f;
// ...
Vector3 upDirection = transform.position - target.position;
Quaternion goalRot = Quaternion.LookRotation(parentDirection, upDirection);
transform.rotation = Quaternion.RotateTowards(transform.rotation, goalRot,
turnVelocity * Time.deltaTime);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.