旋转一个对象(模型)和另一个对象的旋转(手VR)



我正在使一个对象随手的旋转角度旋转。它工作得很好,我可以旋转三维模型对象。不幸的是,现在我只希望对象在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;
}

您想要夹住围绕该轴的旋转。

我制作了一个扩展方法来像这样夹住每个轴,使该功能在项目中的任何地方都可用。

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;

真不敢相信它有多简单。

要使事物只旋转.z轴,您应该保留其他轴。示例:

Transform target;
transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, target.eularAngles.z);

只是使用目标z。

最新更新