Unity3D技术之计算向量的旋转角度
欢迎来到unity学习、unity培训、unity企业培训教育专区,这里有很多U3D资源、U3D 培训视频、U3D教程、U3D常见问题、U3D项目源码,我们致力于打造业内unity3d培训、学习第一品牌。
向量的点乘和叉乘都是很有用的数学工具,不过他们也有局限性。关键是向量点乘可以得到两个向量之间的夹角,而不是旋转角,这个角度是没有方向的,范围是[0-pi],而这往往不是我们想要的,实际问题中我们常常要计算从向量p1沿逆时针方向转到与向量p2方向一致的确切角度,我把这个角度定义为旋转角。旋转角的计算既需要夹角,还需要两个向量的叉乘,以确定p1和p2的角度方向关系。
关于叉乘符号与向量的角度方向关系,请参考《算法导论》,我只给出结论: p1 * p2 = x1y2  - x2 y1 = -p2 * p1
If p1 * p2 is positive, then p1 is clockwise from p2 with respect  to the origin (0, 0); if this cross product is negative, then p1 is counterclockwise      from p2.
另外考虑的是共线(collinear )的问题, arcsine很难处理这个问题,不过arecosine却能够明确的区分0和pi,因此作为特殊情况提前得出结论。
代码如下:文章出处狗刨学习网
1.double getRotateAngle(double x1, double y1, double x2, double y2)
2.{
unity 教程
5.double dist, dot, degree, angle;
6.// normalize
7.dist = sqrt( x1 * x1 + y1 * y1 );
8.x1 /= dist;
9.y1 /= dist;
10.dist = sqrt( x2 * x2 + y2 * y2 );
11.x2 /= dist;
12.y2 /= dist;
13.// dot product
14.dot = x1 * x2 + y1 * y2;
15.if ( fabs(dot-1.0) <= epsilon )
16.angle = 0.0;
17.else if ( fabs(dot+1.0) <= epsilon )
18.angle = nyPI;
19.else {
20.double cross;
21.angle = acos(dot);
22.//cross product
24.// vector p2 is clockwise from vector p1
25.// with respect to the origin (0.0)
26.if (cross < 0 ) {
27.angle = 2 * nyPI - angle;
28.}
29.}
30.degree = angle * 180.0 / nyPI;
32.}
本文有关于两向量的旋转角的计算就这些,希望对读者起到一定的作用。