An effective way to get the angle between two vectors in the same plane?

If I know that the x and z values ​​of the vectors will be the same, so they just wanted to measure the "vertical" angle from the differences in the y plane, is there a more efficient way to do this compared to calculating the point product?

My current code using the dot product method is as follows:

float a_mag = a.magnitude(); float b_mag = b.magnitude(); float ab_dot = a.dot(b); float c = ab_dot / (a_mag * b_mag); // clamp d to from going beyond +/- 1 as acos(+1/-1) results in infinity if (c > 1.0f) { c = 1.0; } else if (c < -1.0) { c = -1.0; } return acos(c); 

I would like to get rid of these square roots

+4
source share
2 answers

Suppose your two vectors live in u = (x, y1, z) and v = (x, y2, z) , and you are interested in the flat angle between the two along a plane stretched over two vectors. You will need to calculate the point product and magnitude, but you can save a few operations:

 uv = xx + y1.y2 + zz u^2 = xx + y1.y1 + zz v^2 = xx + y2.y2 + zz 

So, we must precompute:

 float xz = x*x + z*z, y11 = y1*y1, y12 = y1*y2, y22 = y2*y2; float cosangle = (xz + y12) / sqrt((xz + y11) * (xz + y22)); float angle = acos(cosangle); 
+3
source

If the values ​​of x and z do not change, then the calculation is very simple: just use basic trigonometry.

Let the points (x, y1, z) and (x, y2, z) . You can find out the angle that the vector makes with the ZX plane. Let the angles t1 and t2 respectively. Then:

 w = sqrt(x^2 + z^2) tan(t1) = y1 / w So t1 = atan(y1 / w) Similarly t2 = atan(y2 / w) The angle is (t2 - t1) 

There is one mistake: when both x and z are equal to zero, tan are undefined ... but such a trivial case can be easily handled separately.

Unfortunately, there is no way to avoid the square root.

+1
source

Source: https://habr.com/ru/post/1395485/


All Articles