I have a rigidbody and a point in space, and I’m trying to use Rigidbody.AddTorque
to make the rigidbody attract to the position and rotation of the point. Here’s the code I have so far;
public Rigidbody ObjectToAttract;
[Range(0, 50)]
public float Agressiveness = 10;
[Range(0, 10)]
public float RotationalAgressiveness = 10;
void FixedUpdate()
{
Vector3 Difference = transform.position - ObjectToAttract.transform.position;
ObjectToAttract.AddForce(Difference * Agressiveness - ObjectToAttract.velocity, ForceMode.VelocityChange);
Vector3 AngDifference = AngleDifference(ObjectToAttract.transform.rotation.eulerAngles, transform.rotation.eulerAngles);
ObjectToAttract.AddTorque(AngDifference * RotationalAgressiveness - ObjectToAttract.angularVelocity, ForceMode.VelocityChange); // This line causes issues
}
And here’s the AngleDifference
function;
private Vector3 AngleDifference(Vector3 Angle1, Vector3 Angle2)
{
Vector3 Difference = new Vector3();
Difference.x = Angle2.x - Angle1.x;
if (Difference.x > 180) Difference.x -= 360;
else if (Difference.x < -180) Difference.x += 360;
Difference.y = Angle2.y - Angle1.y;
if (Difference.y > 180) Difference.y -= 360;
else if (Difference.y < -180) Difference.y += 360;
Difference.z = Angle2.z - Angle1.z;
if (Difference.z > 180) Difference.z -= 360;
else if (Difference.z < -180) Difference.z += 360;
return Difference;
}
I have the code for attracting the rigidbody to a specific position working fine, but the code for applying torque to it causes it to spin in seemingly random directions, regardless of the angle I rotate the point to. What am I doing wrong here?