How to determine world to screen position?

Started by
2 comments, last by zedz 16 years, 10 months ago
Hi all, I want to display a bar, say 20 pix wide and 200 pix long floating above an 3D object. I can translate the screen pos to 3D world pos but not the other way around. I translate to the top of the object en I want to convert that position to screen coordinates so I can display the bar there, but each time I convert, my coordinates become corrupt (#INF000). Can someone please help me? Here is some pseudo-code: // ... // Translate to top of object. glTranslate(0.0f, -3.5f, 0.0f); // Get current 3D coordinates fX = 0.0f; fY = -3.0f; fZ = 0.0f; // Convert the 3D coords to screen coords. ConvertWorldToScreen(&fX, &fY, &Z); // ... void ConvertWorldToScreen(float* x, float* y, float* z) { static GLint viewport[4]; static GLdouble modelview[16]; static GLdouble projection[16]; static GLfloat winX, winY, winZ; double worldX, worldY, worldZ; glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, projection); glGetIntegerv(GL_VIEWPORT, viewport); winX = (GLfloat)*x; winY = (GLfloat)*y; winZ = (GLfloat)*z; gluProject(winX, winY, winZ, modelview, projection, viewport, &worldX, &worldY, &worldZ); *x = (GLfloat)worldX; *y = (GLfloat)viewport[3] - (GLfloat)worldY; *z = (GLfloat)worldZ; } </code>
Advertisement
i just copy-pasted your code in my program and it works..
it returns strange numbers, when the object is NOT on screen..
and that is what happens in your code..

camera is, by default, pointing (0, 0, -1), so this:
glTranslate(0.0f, -3.5f, 0.0f);

only moves camera up (world down), but camera still points down the negative Z

your objects is at (0, -3.0f, 0), that is below the camera..
so there is no way, you would see that object on screen (maybe with very big FOV :))
you probably want to translate world by (0, 0, -3.5f) and then position object to (0, 0, -3.0f)..
btw, try to compute screen position only if it CAN be on screen..

Thanks for your reply.

I can see the object on the screen when I run the program.
I tranlate -3.5 on the Y axis in a list when I create the object. When I do this I can do the following:

glBegin(GL_LINES);    glVertex3f(-3.0f, -3.5f, 0.0);    glVertex3f( 3.0f, -3.5f, 0.0);glEnd();


This will draw a line underneath my object. But I want the line to be 200 pixels long and 20 pixels wide. That is why I want to translate from the object's center -3.5 on the y-axis and than draw a 200 pixel long bar there.
after youve gotten the screen position result fro gluProject(..)
u then need to set up a projection matrix with glOrtho(... ) the same size as the screen, see the faq/wiki at www.opengl.org for info
with that u can draw a bar exactly 20x200 pixels at the correct spot

This topic is closed to new replies.

Advertisement