Calculate on which direction is shorter to rotate

Hey. I am using angularVelocity to make a rigidbody rotate. So , sometimes it’s easier to rotate to the target rotation clockwise , sometimes counterclockwise. Why doesn’t this work?


if(targetRotation.eulerAngles.y<transform.eulerAngles.y){
rigidbody.angularVelocity = new Vector3(0,3,0);
}else{
rigidbody.angularVelocity = new Vector3(0,-3,0);
}
if(targetRotation==transform.rotation){
rigidbody.angularVelocity = new Vector3(0,0,0);
}

2 Answers

2

Take a look at Mathf.DeltaAngle or Quaternion.Slerp.

Or depending on your needs, Quaternion.LookRotation may also work.

Some additional info after a quick search:

http://forum.unity3d.com/threads/36377-transform-LookAt-or-Quaternion-LookRotation-on-1-axis-only

But I need it done with angularVelocity because I am performing some physics calculations

–

I think Mathf.DeltaAngle should work then. I've not used it, but it sounds like it should give you a positive or negative value that's the shortest number of degrees to move to get to the target angle.

–

I think this works well assign a target and speed velocity and it’s ok, I use that in my AI systems

lookPos = target.transform.position - transform.position; 
lookPos.y = 0;  
Quaternion nrotation = Quaternion.LookRotation(lookPos); 
transform.rotation = Quaternion.Slerp(transform.rotation, nrotation, speed);