使用2D屏幕坐标gluUnproject获取3D模型坐标

时间:2013-11-28 10:02:15

标签: c++ opengl 3d 2d raytracing

我尝试获取OpenGL模型的3D坐标。我在论坛中找到了这段代码,但我不明白如何检测到碰撞。

-(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? 另一个问题是: 如何在这些碰撞点处理纹理?我想我需要相应的顶点!?

最好的问候

1 个答案:

答案 0 :(得分:0)

该代码将光线从您的近剪裁位置移动到远处的角落位置,然后将其划分为50,并沿着此光线在3D中插入点的所有可能位置。在循环的出口处,在您发布的原始代码中,collisionPointx,y和z是最远点的值。该代码中没有“碰撞”测试。实际上,您需要针对要碰撞的3D对象测试3D坐标。