2013-11-28 124 views
0

我尝试获取OpenGL模型的3D坐标。我在论坛中发现了这个代码,但我不明白碰撞是如何检测到的。使用2D屏幕坐标获取3D模型坐标gluUnproject

-(void)receivePoint:(CGPoint)loke 
{ 

GLfloat projectionF[16]; 
GLfloat modelViewF[16]; 
GLint viewportI[4]; 

glGetFloatv(GL_MODELVIEW_MATRIX, modelViewF); 
glGetFloatv(GL_PROJECTION_MATRIX, projectionF); 
glGetIntegerv(GL_VIEWPORT, viewportI); 

loke.y = (float) viewportI[3] - loke.y; 

float nearPlanex, nearPlaney, nearPlanez, farPlanex, farPlaney, farPlanez; 

gluUnProject(loke.x, loke.y, 0, modelViewF, projectionF, viewportI, &nearPlanex, &nearPlaney, &nearPlanez); 
gluUnProject(loke.x, loke.y, 1, modelViewF, projectionF, viewportI, &farPlanex, &farPlaney, &farPlanez); 

float rayx = farPlanex - nearPlanex; 
float rayy = farPlaney - nearPlaney; 
float rayz = farPlanez - nearPlanez; 

float rayLength = sqrtf((rayx*rayx)+(rayy*rayy)+(rayz*rayz)); 

//normalizing rayVector 

rayx /= rayLength; 
rayy /= rayLength; 
rayz /= rayLength; 

float collisionPointx, collisionPointy, collisionPointz; 

for (int i = 0; i < 50; i++) 
{ 
    collisionPointx = rayx * rayLength/i*50; 
    collisionPointy = rayy * rayLength/i*50; 
    collisionPointz = rayz * rayLength/i*50; 
} 
} 

在我看来有一个休息条件失踪。我什么时候可以找到collisionPoint? 另一个问题是: 如何操作这些碰撞点的纹理?我认为我需要相应的顶点!?

问候

+0

GluUnproject用于采用屏幕坐标并使用当前的ModelView矩阵将它们解除投影到场景中。因此,给出* current *变换矩阵,它给出了屏幕上某个x和y位置的世界坐标。我不太明白你如何使用它来进行物理计算? – Bartvbl

+0

碰撞算法被称为射线追踪。我只想将对象的相应3D像素添加到我的2D触摸位置。 – Philsen

回答

0

这代码利用射线从近剪裁的地方,你在远远的魔神的位置,然后在50分区,并插在你的3D沿着这条射线点的所有可能的位置。在循环结束处,在您发布的原始代码中,collisionPointx,y和z是最远点的值。该代码中没有“碰撞”测试。您实际上需要针对您想要与之碰撞的3D对象测试3D坐标。

+0

没错。我该怎么做? :) – Philsen

+0

通常你在鼠标位置读取深度缓冲区。这会给你一个正常点。只需转换回世界坐标。 –

+0

如果我使用glFragCoord的深度缓冲区,我可以读取带有glreadpixels的z值,对吧?我为什么要做光线追踪? – Philsen