Title pretty much says it all. I'm working on a simple 'lets get used to lwjgl' project involving manipulation of a rubik's cube, and I can't figure out how to tell which side/square the user's pointing at.
|
You'll want to use 3D picking. Here's some code I use in my game. First I cast a ray from my camera. I'm using the mouse, but if you're just using where the user is looking, you can just use the center of the window. This is that code from my camera class:
Then I follow out the ray until it intersects with an object, you can do this with bounding boxes or something similar, since this is specific to your game, I'll let you handle that. Generally this is done by following the ray out (adding the direction of the ray to it's starting point over and over 'till you bump into something). Next you want to see which face is being picked, you can do that by iterating over the triangles in your cube to see if the ray intersects them. The following function does that and returns the distance to the picked face, then I just use the intersected face that's closest to the camera (so you're not picking the back face).
The triangle with the shortest distance is the picked triangle. Also, shameless plug for my game, you should check it out, follow it and vote in the polls I put out occasionally. Thanks! http://byte56.com |
||||
|
|
|
The technique you're looking for is called "picking" or "3D picking." There are several ways to do it; one of the more common ones is to transform a 2D point on the screen into eye space by using the inverse of the projection transformation. This will allow you to generate a ray in view space, which you can use to test for collision with the physical representation of your various bits of scene geometry to determine which object the user 'hit.' You can also use a "picking buffer" (or "selection buffer") which GL has support for. This basically involves writing some unique object identifier into a buffer for every pixel and then simply testing that buffer. The OpenGL FAQ has brief discussions on both (it focuses more on the selection buffer since that's entirely a GL feature; ray picking is API agnostic except perhaps for extracting the active matrices from the pipeline). Here is a more specific example of the ray picking technique (for iOS, but it should translate easily enough). This site has some source code to some of the OpenGL Red Book examples ported to LWJGL, which include a picking demo. See also this question on SO. |
|||||
|