I am attempting to learn OpenGL and LWJGL by making a minecraft clone, but I am stuck
I was able to render blocks easily and have a first-person camera with wasd controls and now I’m trying to be able to place blocks, but I cannot figure out how would I be able to check which cube and which side of that cube I am looking at/is in the center of the screen so I can put another cube adjacent to that cube.
I am using gluPerspective for the 3d perspective and glRotatef to rotate the world, pretty normal stuff
One technique is to use an id-buffer. You draw your scene to two textures at once using a framebuffer. The first texture will be a typical color texture. The second will be a texture that stores integers. Before drawing the scene, you assign a number to each cube face. You pass these numbers in to the shader (uniform variables work for this). The fragment shader will ‘draw’ these numbers to the integer texture, while at the same time doing normal shading to the color texture. When you need to find what is at the mouse cursor, use
glReadPixels().This is all assuming you are using modern OpenGL (3 or better). If you are stuck with the fixed function pipeline (lame), you can also assign a unique color to each cube face, and draw to the back buffer with solid coloring. Make sure to turn off texturing etc. When that’s done, use
glReadPixels()to find what was drawn at the mouse cursor. Then you draw things again as normal and swap buffers. (Here’s some outdated code that shows what I’m talking about: http://www.lighthouse3d.com/opengl/picking/index.php3?color1)Another technique is to ‘cast a ray’ through the screen. Basically, you test a few equations against each shape in your geometry, and if these tests pass, you have an intersection and you know what shape is clicked. I’m not so experienced with this method, so I’ll leave it to someone else to explain if they want to.