![](/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.