- Home /
rotate vector3
I have Vector3 variable and I want to rotate it so that Y-axis will be pointing up. How to do it?
EDIT: sorry, Y-axis has to be 0 (so the resulting Vector is on XY plane)(but it has to have same magniude of course)
You can use this to point your Vector3 in a specific direction smoothly over time
http://docs.unity3d.com/ScriptReference/Vector3.SmoothDamp.html
I dont want to do it smoothly ... i want to calculate it
and what target do I should write as second parameter if I want to do it smoothly ??
Answer by lukas_balaz · Aug 01, 2014 at 02:10 PM
Found my answer:
float mag = v.magnitude;
v -= new Vector3 (0,v.y,0); // set y to 0
v.Normalize();
v *= mag //multiply by mag (so magnitude is same as before)
Answer by robertbu · Aug 01, 2014 at 01:30 PM
Given a vector v at an arbitrary angle, youu can do:
v = Quaternion.FromToRotation(v, Vector3.up) * v;
sorry, I meant that Y axis has to be 0 (so the resulting Vector is in XY plane), my mistake
In that case, the easiest thing to do is to just set the 'y' value of the vector to 0.0. I don't know your application, but you might have to special case the situation when the vector is pointing straight up. Also depending on your application, you may want to normalize the result. Note for changing over time, you can use Vector3.Slerp(), Vector3.Lerp(), or Vector3.RotateTowards().
Just saw your magnitude edit:
var mag : float = v.magnitude;
v.y = 0.0;
v = v.normalized * mag;
For the special case of straight up, you can just create any vector on the xz plane with the right magnitude:
var mag : float = v.magnitude;
if (v == Vector3.up) {
v = Vector3.right * mag;
}
else {
v.y = 0.0;
v = v.normalized * mag;
}
sorry I read your comment 10 seconds after posting it as answer :)