- Home /
How to rotate an object so that y axis faces towards another object?
Can someone help me understand what is the math required to rotate one object so that it's UP vector (the local y-axis) points towards another object?
I know that Transform.LookAt does that, but for the FORWARD vector (the local z-axix), but I want to do the same for the y-axis instead, with some slight modification (dampening how fast it can rotate)
Answer by EvilTak · Dec 20, 2014 at 04:32 AM
Looking at your comment on the other answer, you should use Quaternion.FromToRotation. And after that, use Quaternion.Lerp. Something like this (This code should be in FixedUpdate for smooth results):
Vector3 direction = otherObject.position - transform.position;
Quaternion toRotation = Quaternion.FromToRotation(transform.up, direction);
transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, speed * Time.time);
Here is the result (A cylinder poinsting towards the main camera with speed = 0.1f):
Thanks, this worked awesomely! Here's the result :) http://gfycat.com/WarpedBlueItalianbrownbear
Actually, you can change Vector3.up to transform.up in the 2nd line.
You said "should be in FixedUpdate for smooth results" but wouldn't it be better if you place it in update and use Time.deltaTime ins$$anonymous$$d? Can't get smoother than that, or am i missing something here?
I should rephrase the sentence. It'll make the movement more accurate, no matter what the FPS of the game'll be. Plus, I$$anonymous$$O it's better to do computations in FixedUpdate.
Answer by Kartik1607 · Dec 20, 2014 at 02:59 AM
Hey.
Lets try some coding.
First, we create a public Transform variable to store the target object. (to whom we want to look)
public Transform target;
Now, we want to look at the target. So, we use LookAt function.
void Update () {
transform.LookAt (target.position);
}
This produces this effect.
But, we want the Y axis to point to cube.
If we observe, we can see that Y axis is 90 degree to the direction tree is looking at. So, we simply rotate the tree by 90 degree around X axis.
void Update () {
transform.LookAt (target.position);
transform.Rotate (new Vector3 (1.0f, 0, 0), 90);
}
This makes Y axis point towards the object.
Hm, haha, yeah that works.
However, you see, my intention was to understand how LookAt works so that I can apply it myself in code, because I want it to rotate at a slow pace and not instantly.