Aligning 2 Quaternions Using Torque

Hi, I’m working on improving my math skills, especially with quaternions. A weird behavior came up that I’m curious about…

I’m trying to rotate one object to be ‘near’ identical rotation of a target object using Unity’s torque physics. (I know these aren’t real world accurate or anything… I’d just like it to get it behaving better.) The code I wrote below works fine if I comment out:

myRigid.AddRelativeTorque (newAxis);

and use this line instead (uncomment):

// myRigid.MoveRotation (Quaternion.AngleAxis (newAngle , newAxis));

but obviously that’s not using the torque feature of physics.

Currently the cube is rotating correctly to the camera’s rotation, and then stopping, like it should, but when I change the camera’s rotation from 0.0, 0.0, 0.0 to ANYTHING else the cube is rocking back and forth and BARELY MOVING AT ALL! (It doesn’t decisively go anywhere.)

How do I fix this? Here is the code I wrote:

	private void UsingQuaternions ()
	{
		Quaternion changeRotation = Quaternion.RotateTowards (myRigid.rotation , Camera.main.transform.rotation , 0.0f); // I've played around with the last value (delta) here, I don't think this is causing my problem.
		
		Vector3 newAxis;
		float newAngle;
		changeRotation.ToAngleAxis (out newAngle , out newAxis);
		newAxis.Normalize ();

		float angleBetween = Quaternion.Angle (myRigid.rotation , Camera.main.transform.rotation);

		if (angleBetween < 3.0f)
		{
// This makes the rotation 'gravitate' towards the target area when it gets close.
			myRigid.angularVelocity *= 0.6f;
		}
		else
		{
			myRigid.AddRelativeTorque (newAxis);
			// myRigid.MoveRotation (Quaternion.AngleAxis (newAngle , newAxis));
		}
	}

UsingQuaternions () is called once every FixedUpdate (), just to clarify. :slight_smile:

I’d appreciate any help with this, thanks!

So relativetorque is applying a force around the axes of the rigidbody - given that you apply a force with a maximum magnitude of 1 then I’m not surprised it isn’t moving! Also newAxis as well as being normalized (before you made your call to do so, as well as after…) is the axis that the rotation should occur around - not the direction which movement should occur in. Added to that you need to understand what the rotation of the object is to apply the force.

What you are trying to do is very difficult, effectively you would need to work out how much force to apply around each axis of the actual representation of the object - I’m guessing that’s Vector3.up for AddTorque.

You should check out this answer by @aldonaletto.

My best guess (without trying it) of getting the right kind of thing to apply would be to use:

var requiredRotation = Quaternion.FromToRotation(myRigid.forward, Camera.main.transform.forward);
myRigid.AddTorque(requiredRotation.eulerAngles * someKindOfScalingFactor);

Given the speed of movement with AddForce depends on the mass of the object - I’ve no idea what that scaling factor might be…