简体   繁体   English

在单个平面中获得两个向量之间角度的有效方法?

[英]Efficient way to get the angle between two vectors in a single plane?

If I know for a fact that the x and z values of the vectors will be identical, therefore im only concerned in measuring the 'vertical' angle of from the differences in the y plane, is there a more efficient method to do this compared to computing the dot product? 如果我知道矢量的x和z值是相同的,因此我只关心从y平面的差异测量“垂直”角度,是否有更有效的方法来做到这一点计算点积?

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 love to be able to get rid of these square roots 我希望能够摆脱这些平方根

Suppose that your two vectors live at u = (x, y1, z) and v = (x, y2, z) , and you're interested in the planar angle between the two along the plane spanned by the two vectors. 假设您的两个向量位于u = (x, y1, z)v = (x, y2, z) ,并且您对两个向量所跨越的平面之间的平面角度感兴趣。 You'd have to compute the dot product and the magnitude, but you can save a few operations: 您必须计算点积和幅度,但您可以保存一些操作:

u.v = x.x + y1.y2 + z.z
u^2 = x.x + y1.y1 + z.z
v^2 = x.x + y2.y2 + z.z

So we should 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);

If the values of x and z are unchanged, then the calculation is very easy: just use basic trigonometry. 如果x和z的值不变,则计算非常简单:只需使用基本三角法。

Let the points be (x, y1, z) and (x, y2, z) . 设点为(x, y1, z)(x, y2, z) You can find out the angle a vector makes with the ZX-plane. 您可以找到矢量与ZX平面形成的角度。 Let the angles be t1 and t2 respectively. 设角度分别为t1t2 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's one pitfall: When both x and z are zero, the tan s are undefined... but such a trivial case can easily be handled separately. 有一个陷阱:当x和z都为零时, tan s是未定义的......但是这样一个简单的情况可以很容易地单独处理。

Unfortunately, there seems to be no way to avoid the square root. 不幸的是,似乎没有办法避免平方根。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM