我需要计算3点之间的角度。为此,我执行以下操作:
Math.acos
对于没有超过180度角度的形状,这似乎工作正常,但是如果形状有这样的角,则计算短边。这是一个说明我的意思(红色值是错误的)的例证:
这是进行计算的代码:
// Pythagoras for calculating distance between two points (2D)
pointDistance = function (p1x, p1y, p2x, p2y) {
return Math.sqrt((p1x - p2x)*(p1x - p2x) + (p1y - p2y)*(p1y - p2y));
};
// Get the distance between the previous, current and next points
// vprev, vcur and vnext are objects that look like this:
// { x:float, y:float, z:float }
lcn = pointDistance(vcur.x, vcur.z, vnext.x, vnext.z);
lnp = pointDistance(vnext.x, vnext.z, vprev.x, vprev.z);
lpc = pointDistance(vprev.x, vprev.z, vcur.x, vcur.z);
// Calculate and print the angle
Math.acos((lcn*lcn + lpc*lpc - lnp*lnp)/(2*lcn*lpc))*180/Math.PI
代码中是否有问题,我忘了做某事,还是应该以完全不同的方式完成?
答案 0 :(得分:4)
你的数学和计算是完美的。你遇到了大多数人在计算器上遇到的同样问题,这就是方向。我要做的是使用此代码找出前两个点所形成的向量的左侧或右侧的点,我从
中找到Determine which side of a line a point lies
isLeft = function(ax,ay,bx,by,cx,cy){
return ((bx - ax)*(cy - ay) - (by - ay)*(cx - ax)) > 0;
}
ax和ay组成你的第一个点bx到你的第二个cx cy你的第三个。
如果它在左侧,则只需将角度加180即
答案 1 :(得分:1)
我有一个工作但不一定简短的例子说明这是如何工作的:
var point1x = 0, point1y = 0,
point2x = 10, point2y = 10,
point3x = 20, point3y = 10,
point4x = 10, point4y = 20;
var slope1 = Math.atan2(point2y-point1y,point2x-point1x)*180/Math.PI;
var slope2 = Math.atan2(point3y-point2y,point3x-point2x)*180/Math.PI;
var slope3 = Math.atan2(point4y-point3y,point4x-point3x)*180/Math.PI;
alert(slope1);
alert(slope2);
alert(slope3);
var Angle1 = slope1-slope2;
var Angle2 = slope2-slope3;
alert(180-Angle1);
alert(180-Angle2);
(见http://jsfiddle.net/ZUESt/1/)
要解释多个步骤,slopeN
变量是各个线段的斜率。 AngleN是在每个连接点处转动的量(即点N + 1)。正角度是右转弯,负角度是左转弯。
然后,您可以从180减去此角度,以获得所需的实际内角。
应该注意的是,这个代码当然可以被压缩,而五行只是输出变量来查看正在发生的事情。我会让你担心优化它以供你自己使用,这是一个概念证明。
答案 2 :(得分:0)
您需要检查边界条件(显然,如果点是共线的)并应用正确的计算来查找角度。 此外,三角形不能具有大于180度的任何(内部)角度。三角形的角度之和为180度。