I have a rigidbody ObjectToAttract and an empty gameobject with a script attached to it. I would like to apply torque to the rigidbody in order to align its rotation with the empty gameobject. Here’s the basic code for the script;
Quaternion AngDifference = Quaternion.Inverse(ObjectToAttract.transform.rotation) * (transform.rotation);
Vector3 AngDiffMovement = RectifyAngleDifference(AngDifference.eulerAngles);
ObjectToAttract.AddTorque(AngDiffMovement - ObjectToAttract.angularVelocity, ForceMode.VelocityChange);
And here’s the RectifyAngleDifference function;
private Vector3 RectifyAngleDifference(Vector3 angdiff)
{
if (angdiff.x > 180) angdiff.x -= 360;
if (angdiff.y > 180) angdiff.y -= 360;
if (angdiff.z > 180) angdiff.z -= 360;
return angdiff;
}
For some angles of the empty object the script works perfectly fine. But for others the rigidbody wobbles around in seemingly random directions. How can I fix that?
I have a separate revision of the above code;
Quaternion AngDifference = Quaternion.FromToRotation(ObjectToAttract.transform.up, transform.up);
Vector3 AngDiffMovement = RectifyAngleDifference(AngDifference.eulerAngles);
ObjectToAttract.AddTorque(AngDiffMovement - ObjectToAttract.angularVelocity, ForceMode.VelocityChange);
Which is significantly more stable, however it ignores an entire axis of rotation.