- Home /
Find rotation between up and two vectors
Hi guys,
this one's probably really simple and I'm just being dense but I need to find the gradient of a line between vector a (Xa, Ya) and vector b (Xb, Yb). I need to instantiate a game object with the rotation which is consistent with the line that runs from point A to B. I need to find the gradient as degrees so I can apply the rotation to the Z axis of my GameObject so as 0 is vertically up, 45 is up-right, 90 is right etc.
I think I'm just being dense but any help would be appreciated.
Thanks!
Answer by cjdev · Feb 04, 2016 at 09:05 AM
I'm not entirely sure if I've got you right but if you are looking to find the angle that the line segment makes on a 2D plane with an axis you can make a triangle out of the change in X coordinates for a side, and the Y, and then use the tangent of the opposite side over the adjacent to find the angle.
That's what I was doing but It was only working for me between 0 and 90 degrees.
public Vector3 findRotation(Vector3 a, Vector3 b) { float x, y, rot; x = a.x - b.x; x = $$anonymous$$athf.Sqrt(x * x); y = a.y - b.y; y = $$anonymous$$athf.Sqrt(y * y); rot = $$anonymous$$athf.Rad2Deg * $$anonymous$$athf.Atan (x / y); Vector3 rotation = new Vector3 (0, 0, rot); return rotation; }
obviously when I get beyond 90 degrees that becomes an issue and it just calculates it as if it were between 1-90 again.
nvm I don't know why I was making the x and y values positive :') so dense.
Your answer
Follow this Question
Related Questions
Clamping Vector3 2 Answers
C# Raycast from Object direction (z-axis) + another Vector3 1 Answer
How to make Y-Axis face away from a position? 2 Answers