我正在使用openGL(一个房子)做一个场景。我想做一些碰撞检测,主要是在房子的墙壁。 我尝试了以下代码:
// a plane is represented with a normal and a position in space
Vector planeNor(0,0,1);
Vector position(0,0,-10);
Plane p(planeNor,position);
Vector vel(0,0,-1);
double lamda; // this is the intersection point
Vector pNormal; // the normal of the intersection
// this method is from Nehe's Lesson 30
coll= p.TestIntersionPlane(vel,Z,lamda,pNormal);
glPushMatrix();
glBegin(GL_QUADS);
if(coll)
glColor3f(1,0,0);
else
glColor3f(1,1,1);
glVertex3d(0,0,-10);
glVertex3d(3,0,-10);
glVertex3d(3,3,-10);
glVertex3d(0,3,-10);
glEnd();
glPopMatrix();
讷赫的方法:
#define EPSILON 1.0e-8
#define ZERO EPSILON
bool Plane::TestIntersionPlane(const Vector3 & position,const Vector3 & direction, double& lamda, Vector3 & pNormal)
{
double DotProduct=direction.scalarProduct(normal); // Dot Product Between Plane Normal And Ray Direction
double l2;
// Determine If Ray Parallel To Plane
if ((DotProduct<ZERO)&&(DotProduct>-ZERO))
return false;
l2=(normal.scalarProduct(position))/DotProduct; // Find Distance To Collision Point
if (l2<-ZERO) // Test If Collision Behind Start
return false;
pNormal= normal;
lamda=l2;
return true;
}
Z最初为(0,0,0),每当我将相机移向平面时,我将其z分量减小0.1(即Z.z- = 0.1)。 我知道问题出在vel矢量上,但我无法弄清楚正确的值应该是什么。有人可以帮帮我吗?
答案 0 :(得分:2)
在不理解数学的情况下,几乎不可能得到这样的东西。尝试更简单的测试版本,假设z = 0平面和+ z轴运动,使其工作,然后再看一般情况。
答案 1 :(得分:0)
感谢您的帮助。
我再次查看了代码,并将碰撞检测方法更改为以下内容:
//startPoint: the ray's starting point.
//EndPoint: the ray's ending point.
//lamda: the intersection point.
bool Plane::TestIntersionPlane(const Vector3& startPoint,const Vector3& Endpoint, double& lamda)
{
double cosAlpha=Endpoint.scalarProduct(normal); // calculates the angle between the plane's normal and the ray vector.
// Determine If Ray Parallel To Plane
if ((cosAlpha<ZERO)&&(cosAlpha>-ZERO))
return false;
// delta D is the plane's distance from the origin minus the ray's distance from the origin.
double deltaD = distance - startPoint.scalarProduct(normal); //distance is a double representing the plane's distance from the origin.
lamda= deltaD/cosAlpha;// distance between the plane and the vector
// if the distance between the ray and the plane is greater than zero then they haven't intersected.
if(lamda > ZERO)
return false;
return true;
}
这似乎适用于所有飞机,除非光线离飞机太远。例如,如果平面位于z = -10并且光线的起始点是:0,0,3并且它的结束点是0,0,2那么这被检测为碰撞但是当我将光线移动到开始时(0) ,0,2)和结束(0,0,1)它没有被检测为碰撞。 数学似乎对我来说是正确的,所以我不知道如何处理这个问题。