简体   繁体   中英

Get 3D model coordinate with 2D screen coordinates gluUnproject

I try to get the 3D coordinates of my OpenGL model. I found this code in the forum, but I don´t understand how the collision is detected.

-(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;
}
}

In my opinion there a break condition missing. When do I find the collisionPoint? Another question is: How do I manipulate the texture at these collision point? I think that I need the corresponding vertex!?

best regards

That code takes the ray from your near clipping place to your far at the position of your loke then partitions it in 50 and interpolates all the possible location of your point in 3D along this ray. At the exit of the loop, in the original code you posted, collisionPointx, y and z is the value of the far most point. There is no "collision" test in that code. you actually need to test your 3D coordinates against a 3D object you want to collide with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM