楼主的公式错了:角度余弦 = 向量1 点乘 向量2 / (|向量1|*|向量2|);如果没错,那么函数里面的公式也写错了:float c=(float)sqr(dx1*dx1+dx2*dx2+dy1*dy1+dy2*dy2);
|向量1|*|向量2|=sqr(dx1*dx1+dy1*dy1)*sqr(dx2*dx2+dy2*dy2)
sqr(dx1*dx1+dx2*dx2+dy1*dy1+dy2*dy2)不等于sqr(dx1*dx1+dy1*dy1)*sqr(dx2*dx2+dy2*dy2)
至于求大于180度的问题我也遇到了,希望高手解答!
|向量1|*|向量2|=sqr(dx1*dx1+dy1*dy1)*sqr(dx2*dx2+dy2*dy2)
sqr(dx1*dx1+dx2*dx2+dy1*dy1+dy2*dy2)不等于sqr(dx1*dx1+dy1*dy1)*sqr(dx2*dx2+dy2*dy2)
至于求大于180度的问题我也遇到了,希望高手解答!
2 算角度
3 考虑是否2PI-角度 若我没有记错的话 上面是可行的
另外我算角度是arctg
nB = normalize(B)c1 = cross(nA, nB)
c2 = cross(-nA, nB)d = dot(nA, nB)
r = acos(d)如果c1和c2相等则大于180度,否则c1和c2相反
根据这个条件对r进行相应调整即可
算角度用arctg是不行的,因为arctg的值域是(-pi/2,pi/2),这里没有等号。那么-pi/2和pi/2这些角度就永远求不出来了。
兄弟,我对你这种判断方法表示怀疑。现在顺时针、逆时针的判断很好判断,可以通过
((dx1*dy2-dy1*dx2)>0) 就是顺时针,反之逆时针。只是夹角大于180度的情况不好判断。
||a*b|| = ||a||*||b||*sin& (&为夹角)来判断。
struct Point
{
float x,y;
};float vectorMag(const Point &start, const Point &end)
{
return sqrtf((start.x - end.x) * (start.x - end.x) +
(start.y - end.y) * (start.y - end.y));
}float DotProduct(const Point &cen, const Point &first, const Point &second)
{
dx1 = first.x - cen.x;
dx2 = second.x - cen.x;
dy1 = first.y - cen.y;
dy2 = second.y - cen.y; return dx1 * dx2 + dy1 * dy2;
}//假定逆时针为正向
bool SignByCrossProduct(const Point &cen, const Point &first, const Point &second)
{
dx1 = first.x - cen.x;
dx2 = second.x - cen.x;
dy1 = first.y - cen.y;
dy2 = second.y - cen.y;
if(dx1 * dy2 - dy1 * dx2 > 0) return true;
return false;
}//夹角范围[-PI, PI]
float Angle(Point cen,Point first,Point second)
{
float dx1,dx2,dy1,dy2;
float angle;
float mag = vectorMag(cen, first) * vectorMag(cen, second);
angle = (float)acos(DotProduct(cen, first, second) / mag); bool sign = SignByCrossProduct(cen, first, second);
if (!sign) angle = -angle; return angle;
}
float Angle_180(Point cen,Point first,Point second)
{
float dx1,dx2,dy1,dy2;
float angle;
float mag = vectorMag(cen, first) * vectorMag(cen, second);
angle = (float)acos(DotProduct(cen, first, second) / mag); bool sign = SignByCrossProduct(cen, first, second);
if (sign)
{
angle = 2 * PI - angle;
}
else
{
angle = angle - 2 * PI;
} return angle;
}
if (sign)
{
angle = 2 * PI - angle;
}
else
{
angle = angle - 2 * PI;
} 兄弟,你这里判断有问题的。假设sign为true时,只有 angle 大于180度时,才需要angle = 2 * PI - angle; 否则应该直接返回angle.
回个帖吧 我结贴
二维: GDI、GDI+
三维: osg
a = atan2(x,y) //0~90度 的弧度表示
其他根据象限处理
两角相减,得到角度差 d
统一化为 0~360 或者 -180 ~180
方法2
求向量点积,可以求夹角出余弦。和360 的差是较大的角。