2013-11-28 126 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