LookRotation/LookAt problem

I have a character that I want to manually animate by rotating joints (LookAt/LookRotation) based on the position of a cube in the scene. For example, I want to rotate the LeftHip transform of this character so that it points to the cube.

822437--30483--$LegToCube.png

Here’s my code:

void Update () 
{
   Quaternion q = Quaternion.LookRotation(target.transform.position - this.transform.position  , transform.up);
   transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * 10f); 

   /* If rotating using LookAt */ 
   //transform.LookAt(target.transform.position);
}

At first glance, everything works fine. But when I start moving the cube back and forth for a couple of times, the leg starts twisting along the forward axis even if it’s still pointing to the cube. When I use the LookAt function, it starts to twist once I move the cube to the back, and rotates back to the proper position when I move the cube forward.

822437--30486--$Screenshot - 2_7_2012 , 5_58_38 PM.png

Any ideas on why the transform is rotating that way?

Are you specifying an ‘up’ vector?

The thing about ‘look at’ is it doesn’t not completely describe an orientation, you need to specify the orthogonal vector which describes the local ‘up’.

Well, I did specify an “up” vector in the LookRotation function but not for the LookAt version. Thanks for pointing that out. :slight_smile:

My code looks like this now:

void Update () 
{
   /* LookRotation version */ 
   //Quaternion q = Quaternion.LookRotation(target.transform.position - this.transform.position  , transform.up);
   //transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * 10f); 
   transform.LookAt(target.transform.position, transform.up);
}

Now, the two methods work almost the same. However, the transform will eventually twist particularly when I randomly move the cube around the scene. Maybe I need to use the initial rotation somewhere in my code. What do you think?

If you mean caching the original rotation and using that for the ‘up’ that sounds like a reasonable solution to your problem.

Thanks for explaining the "up’ vector. No more twisting joints. Here’s my code if anyone’s interested.

void Start () 
{
	originalUp = this.transform.up; 
}

void Update ()	
{
	transform.LookAt(target.transform.position, originalUp);
	/* Using LookRotation */
	//Quaternion q = Quaternion.LookRotation(target.transform.position - this.transform.position  , originalUp);
	//transform.localRotation = Quaternion.Slerp(transform.localRotation, q, Time.deltaTime * 10f); 
}

The next step now is to apply this code to all of the character’s joints.

I LOVE YOU. You’ve solved my problem. Your “this.transform.up” saved my a**. I was trying a solution from a couple of days… Thank you so much!