- Home /
Rotate an object so its x axis would align with a vector
It's 3 am, I'll try to be clear... transform.position is the vector start point, let's say A(x,y,z). B(a,b,c) is the end of the vector. Consider this vector as a line in space, direction is irrelevant. Now, how should I rotate the object I have so its x axis would align with the vector AB? I mean, through code, using c#. If I know A and B, how would I calculate the transform.rotate for the object? Thank you in advance.
Answer by robertbu · Dec 09, 2014 at 01:13 AM
Vector3 v = B - A;
Quaternion q = Quaternion.FromToRotation(transform.right, v);
transform.rotation = q * transform.rotation;
Or simpler:
Vector3 v = B - A;
transform.rotation = Quaternion.FromToRotation(Vector3.right, v);
You're awesome! Thank you, I'm going to crash in my bed now UwU But you, however, have an amazing day!
6 years later and I too found myself in this situation... You saved my night
Exactly one year to the day later, I, too, find myself in the situation.
Answer by David_Biggs · Dec 09, 2014 at 02:23 AM
transform.right = B-A;
Nice shortcut, and easier to understand than setting transform.rotation to some Quaternion.LookRotation() that would get the angle right.
Answer by Vitaly-Abilevich · Sep 13, 2017 at 11:16 PM
Thanks, this works perfect, is there a way to add a Linear Interpolation?
Vector3 v = go.transform.position - transform.position;
Quaternion q = Quaternion.FromToRotation(-transform.up, v);
// Changed next line for the last one
//transform.rotation = q * transform.rotation;
transform.rotation = Quaternion.Lerp(transform.rotation, q, Time.deltaTime * alignSpeed);
And with this change weird stuff happens