- Home /
Angle between two vector3 relative to a certain point
What I'm trying to do here is calculate the angle of a slope in order to check if the character actually is able to walk up the slope.
As seen in the image, I have two points that form a line, and would like to calculate the angle between that line and the horizontal axis (It's a 2D game, if that matters).
I'm not really sure how to approach it, as Vector3.Angle does not do what I want to do as It seems to calculate the angle taking (0,0,0) as a reference, and I need to take the bottom red dot as a reference to calculate the angle between the horizontal axis and the top red dot.
Answer by robertbu · Aug 17, 2013 at 04:53 AM
Let's say the bottom red dot is pos1, and the top dot pos2. You can use Vector3.Angle:
var angle = Vector3.Angle(pos2 - pos1, Vector3.right);
Another solution is to use Mathf.Atan2():
var v = pos2 - pos1;
angle = Mathf.Atan2(v.y, v.x);
Note that both of these assume the angle as you presented it. For example if the character can move backwards and the angle is like this:
You will have to do additional checks and processing. Also Vector3.Angle() is unsigned, so if the slope goes downward, you will need additional code.
Atan2 will take care of the sign. That is why it is preferred in most program$$anonymous$$g languages over Atan. The returned angle will respect the quadrant so the value will always be adjusted (considering +ve in the anticlockwise direction, if I remember correctly). You do not have to do worry about downward slopes with Atan2.
Oh, right, I think I understand the reasoning behind this. Thank you, I will try to implement it tomorrow (It's late for me) and then come back to comment :)
@alok1974 - Unity's version of Atan2() goes from 180 to -180, so the downward slope is not a problem, but at the other side, (if needed) he would have to deal with the 180/-180 boundary. In addition Atan2() return radians, so everything always has to be multiplied by $$anonymous$$athf.Rad2Deg.
@robertbu - I$$anonymous$$HO, the other side will not be a problem. I know that Atan2 returns a value between -180 and 180, and that covers the whole 360. For the left side it will always return an angle > 90 and the sign will tell whether it is up or down. Negative is down, positive is up. For the right side, same logic for the signs but the value will be < 90. I think that this can cover all the four quadrants and hence with a return from Atan2, one can always deter$$anonymous$$e the angle and hence direction. Please look at the attached picture.
Thank you two for the info, I'm taking note here. I used the Atan2 and it worked really well, thanks a lot!
Your answer
Follow this Question
Related Questions
Relative Rotation 1 Answer
Calculate vector exactly between 2 vectors 4 Answers
how detect the angle of collision on disc object ? 1 Answer
Position from rotation problem. 1 Answer
Having Trouble with Vector3.Angle 1 Answer