Converting from 3D to 2D coordinates question
Im using OpenGL with c++ to make a game. and right now, im wondering how i would be able to turn 3D coordinates into 2D positions for example: drawing a 2D health bar over a 3D model's head, or something along those lines. xD
so anyways, im wondering how i would be able to set this up where it can be used in SFML. right now im looking up some information but i dont completely understand the methods...
Basicaly, im asking how would i make 3D opengl coordinates con开发者_运维百科vert to 2D coordinates onto the screen using SFML
im also wondering how i would convert 2D coordinates back to 3D, just so i know that too.
also some example code would be nice, just so i get a better picture
thanks for reading
-Molma
Since you're using OpenGL, I'd suggest gluProject
for mapping from 3D to 2D and gluUnProject
for mapping from 2D to 3D (note @ChrisF's comment on unprojecting).
Though I gotta admit, I got no real experience with OpenGL, I just know the terminology for what you wanted and googled for it. :)
The usual approach for drawing health bars and this like is transforming some bounding volume (bounding box, bounding sphere, etc.) or an anchor point into screen space. This is easy enough, since you only have to follow the OpenGL transformation pipeline:
clip_position = Projection_Matrix * Modelview_Matrix * vertex_position
viewport_position.{x,y} = viewport.{x,y} + viewport.{width,height} * (0.5 + clip_position.{x,y} / 2)
2D to 3D is not possible without supplying extra information.
This short text explains the basics of 2D projection of 3D coordinates. The other way around is a bit more difficult because you have only two known values (the 2D coordinates) and that is not enough exactly extract the three coordinates. The best you can get is a line (starting at the viewer, going through the point on the screen and extending to infinity. The 3D point can basically be anywhere behind the point on the screen. But if you know something extra, the distance to the camera or a part of the position of the thing of which you know the 2D coordinates, you can determine the 3 coordinates.
You just have to do the same transform as openGL does to the coordinates. This typically involves the following steps:
multiply it by the translation matrix (i.e. camera matrix). This puts your 3d coordinate in a screen oriented coordinate system
multiply it by the projection matrix. This will project the coordinate onto the screen
Presumably you have those matrices, since you have to load them in openGL, but you can also ask for them.
精彩评论