Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
783 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You first have to understand how to compute angle between two vectors and there are several of them. I will give you what I think is the simplest.

  1. Given v1 and v2, their dot product is: v1x * v2x + v1y * v2y
  2. The norm of a vector v is given by: sqtr(vx^2+vy^2)

With this information, please take this definition:

dot(v1, v2) = norm(v1) * norm(v2) * cos(angle(v1, v2))

Now, you solve for angle(v1, v2):

angle(v1, v2) = acos( dot(v1, v2) / (norm(v1) * norm(v2)) )

Finally, taking the definitions given at the beginning, then you end up with:

angle(v1, v2) = acos( (v1x * v2x + v1y * v2y) / (sqrt(v1x^2+v1y^2) * sqrt(v2x^2+v2y^2)) )

Again, there are many ways to do this, but I like this one because it is helpful for dot product given angle and norm, or angle, given vectors.

The answer will be in radians, but you know that pi radians (that is 3.14 radians) are 180 degrees, so you simply multiply by the conversion factor 180/pi.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...