OpenGL 求反射向量 download here: http://rorger.download.youkuaiyun.com/ //rorger, 2011 //LineReflect.cpp //二维求反射向量 #include "myglbase.h" #include "glut.h" #include "windows.h" #include "math.h" int GetLinesIntersect(Point2 A, Vector2 c,Point2 B,Vector2 n, double& tHit,Point2& PHit) { if (n*c==0) { //射线与直线平行 return 0 ; } else { tHit= (n*(B-A))/(n*c); PHit=A+c*tHit; if(n*c >0) { return 1; //射线沿着法向量方向 } else { return -1 ; //射线与法向量相反 } } } //取得a向量经过法向量为n的直线的反射后的向量r //结果保存在r中; int GetReflectVector(Vector2 a,Vector2 n, Vector2& r) { if(n.GetLength() != 0) { n.Normalized(); r=a-2*(a*n)*n; return 1; } else return 0 ; } void testReflectVector() { //射线 Point2 A(-3,4); Vector2 c(6,-2); //直线 Point2 B(0,0); Point2 D(5,5); Vector2 n=((Vector2)(D-B)).GetNormalVector(); //pay attention to the orientation double tHit; Point2 pHit; GetLinesIntersect(A,c,B,n,tHit,pHit); Vector2 r ; GetReflectVector(c,n,r); Point2 AR=pHit+r*1; Point2 N = pHit + n*1; glBegin(GL_LINES); glColor3f(0.0,0.0,1.0); glVertex2d(B.x,B.y); glVertex2d(D.x,D.y); glColor3f(0.0,1.0,0.0); glVertex2d(A.x,A.y); glVertex2d(pHit.x,pHit.y); glVertex2d(pHit.x,pHit.y); glVertex2d(AR.x,AR.y); glEnd(); glEnable(GL_LINE_STIPPLE); glLineStipple(1,0x00e1); glBegin(GL_LINES); glColor3f(0.0,1.0,1.0); glVertex2d(pHit.x,pHit.y); glVertex2d(N.x,N.y); glEnd(); glDisable(GL_LINE_STIPPLE); glColor3f(1.0,1.0,0.0); glBegin(GL_POINTS); glVertex2d(pHit.x,pHit.y); glEnd(); } 看看效果吧: