Archived

This topic is now archived and is closed to further replies.

McEck

Selecting object with mouse

Recommended Posts

what is the best way todetect on which object in worldspace the mouse is pointing? i have programmed a rubix cube, you know the cube where each side has a color and 9 little cubes, you have to fiddle around to complete it after you mixed it... so i want to implement mouse-control, keyboard is very complicated to do (not in code but in game ), now i have to know which little cube the curser grabs. i tested on example included the dx8 sdk, but it didn''t work. would be nice if you have some solutions..

Share this post


Link to post
Share on other sites
Another way that works great in OpenGL (I haven''t done it yet in DX8, so I can''t tell you the optimal way):

render the scene with a unique color for every object and then read that color back to determine the object.

For example, for 255 objects or less, render each object as RGB(ObjectID, 0, 0). Then read the red value of the pixel under the mouse. The red value = ObjectID.

One optimization is to only render that one pixel, if you do that, the texture read should be less expensive.

Share this post


Link to post
Share on other sites
There are a few ways of doing this. The easiest is to use D3DXVec3Project(), and transform the objects position into screen space, and check to see if its close to the mouse cursor. This is fast, and easy, but if the object is far away, it is inaccurate.

The second method is to use D3DXVec3Unproject(). It is fairly easy, once you understand what is going on. First, create 2 D3DXVECTORs. Fill the .x and .y values of both with the current mouse position. Then, in the first vector, put 0.0f in the .z, and in the second put 0.99f in .z. Call D3DXVec3UnProject() twice, once for each vector. You now have a line stretching from the front clip plane to the far clip plane. you can use these values for functions like D3DXBoundSphereProbe(), D3DXPlaneLine Intersect(), etc. This method is obviously more complicated, but gives wonderful results.

Hope that helps.

Z.

Share this post


Link to post
Share on other sites
Just read the rest of your post =). If you use D3DXBoundSphereProbe(), or something similar, and loop through every cube, you will probably get more than one result (the line will go through more than one cube). To solve this, create an STL vector, and when you find an intersection, add the cube''s ID number to that. Then, when you are done checking all objects, loop through every intersection, and use D3DXVec3Project() on each objects position, and find the one with the lowest projected .z value. That is the one that is closest to the camera, and is the one you need to pick.

Z.

Share this post


Link to post
Share on other sites