我正在使物體隨著手的旋轉角度旋轉。它運行良好,我能夠旋轉 3D 模型物件。不幸的是,現在我只希望物件在其 z 軸上旋轉。我正在嘗試使用Quaternion.Euler (0, 0, rot.eulerAngles.z);但不起作用并且模型在所有 3 個軸上旋轉。我如何解決它?
public GameObject targetHand;
[Header ("3D Model")]
public GameObject powerSwitch;
[Header ("Hand to 3D Model")]
public float activationDistance;
private Quaternion currentRot;
private Vector3 startPos;
private bool offsetSet;
void Update () {
if ((IsCloseEnough ())) {
Rotate ();
} else {
offsetSet = false;
}
}
void Rotate () {
SetOffsets ();
Vector3 closestPoint = Vector3.Normalize (targetHand.transform.position - powerSwitch.transform.position);
var rot = Quaternion.FromToRotation (startPos, closestPoint);
rot = Quaternion.Euler (0, 0, rot.eulerAngles.z); //Not working when I do this, why?
powerSwitch.transform.rotation = rot * currentRot;
}
void SetOffsets () {
if (offsetSet)
return;
startPos = Vector3.Normalize (targetHand.transform.position - powerSwitch.transform.position);
currentRot = powerSwitch.transform.rotation;
offsetSet = true;
}
bool IsCloseEnough () {
if (Mathf.Abs (Vector3.Distance (targetHand.transform.position, powerSwitch.transform.position)) < activationDistance)
return true;
return false;
}
uj5u.com熱心網友回復:
您想限制圍繞該軸的旋轉。
我制作了一個擴展方法來像這樣夾緊每個軸,使該功能在專案中的任何地方都可用。
public static class MyExtensions // Name it what you like I just use this
{
public static Quaternion ClampRotationAroundZAxis(this Quaternion q)
{
if (!Mathf.Approximately(q.w, 0f)) // Cannot divide by 0f
{
// Check values are not 0f before trying to divide them
q.x = !Mathf.Approximately(q.x, 0f) ? q.x /= q.w : q.x;
q.y = !Mathf.Approximately(q.y, 0f) ? q.y /= q.w : q.y;
q.z = !Mathf.Approximately(q.z, 0f) ? q.z /= q.w : q.z;
q.w = 1f;
}
// Clamp other rotations
q.x = 0f;
q.y = 0f;
return q; // Return self
}
}
// Usage
rotation.ClampRotationAroundZAxis();
編輯:向 OP 顯示使用情況
如果我讓它們以正確的方式進行匹配,您可以像這樣匹配它,否則在設定時交換順序 dir
Vector3 dir = (powerSwitch.transform.position - targetHand.transform.position).normalized;
Quaternion rot = Quaternion.LookRotation(dir, Vector3.up).ClampRotationAroundZAxis();
powerSwitch.transform.rotation = rot;
uj5u.com熱心網友回復:
簡直不敢相信這是多么簡單。
要旋轉事物只是.z軸,您應該保留其他軸。例子 :
Transform target;
transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, target.eularAngles.z);
僅使用目標 z。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/365051.html
上一篇:unity3d將物件移動到觸摸點
下一篇:嘗試從單獨的腳本中獲取int變數
