Alex Rivera | Logout

How to calculate the angle of a vector from the vertical?

Asked 2010-08-09T15:51:54.077
11

Im trying to find out the angle (in degrees) between two 2D vectors. I know I need to use trig but I'm not too good with it. This is what I'm trying to work out (the Y axis increases downward): alt text

I'm trying to use this code at the moment, but it's not working at all (calculates random angles for some reason):

private float calcAngle(float x, float y, float x1, float y1)
{
    float _angle = (float)Math.toDegrees(Math.atan2(Math.abs(x1-x), Math.abs(y1-y)));
    Log.d("Angle","Angle: "+_angle+" x: "+x+" y: "+y+" x1: "+x1+" y1: "+y1);
    return _angle;
}

These are my results (There constant when providing a constant position, but when I change the position, the angle changes and I can't find any link between the two angles):

Position 1: x:100 y:100 x1:50 y1:50 Angle: 45

Position 2: x:92 y:85 x1:24 y1:16 Angle: 44.58

Position 3: x:44 y: 16 x1:106 y1:132 Angle: 28.12

Edit: Thanks everyone who answered and helped me figure out that was wrong! Sorry the title and the question was confusing.

Edit
Report

1 Answer

0

Are you using integers? Cast the arguments as doubles, and I would use fabs on the result, not the arguments. The result will be in radians; to get degrees, use:

res *= (360.0/(2.0*Math.PI));

answered 2010-08-09T15:56:52.703

Your Answer