Ray Picking

Started by
2 comments, last by yaroslavd 19 years, 3 months ago
Hi, guys. I'm a 3D newb. I'm using C# and DX9.Net. I researched the technique of ray picking, but there are some things I'm unclear about. Here's what I understand so far, and what I don't: 1. Use Vector3.Unproject() to convert the screen coordinates to a 3d ray. I don't understand some of the arguments, however: viewport - I'm assuming this is the picturebox/whatever. But why does the method need this? Also, the vector I perform this method on, is it (x,y,0) or what? 2. Find triangle and U,V coords of intersection between the mesh and the ray. Now, I can use Mesh.Intersect((x,y,0),ray,IntersectionInfo) to find the index of the triangle and its UV coords. However, I have no idea how to get the actual triangle or the vertices of the triangle - I only know its index. Furthermore, how do I figure out the position of the intersection based on the UV coords? Ultimately, I want to find the exact position of the intersection in Mesh coords. Thanks for helping me. PS - Is the origin of the Mesh returned by Mesh.Sphere at the center of the sphere?
Advertisement
To do picking you need to convert the cursor position, which is in 2D space, into the 3D world and also calculate a direction ray. The position is converted by doing the inverse of your normal transformations. Normally you go from model to world to view space but this time you need to reverse that, hence the unproject. The z position is unknown though as the cursor is on a 2D plane, however you can get it from the camera position. To calculate the ray you need to know the direction the camera is facing. See also: Picking
------------------------See my games programming site at: www.toymaker.info
Thanks. I think I understand it much better now. However, I feel like Vector.Unproject can do some of the work for me. What I don't understand is whether it returns rayPos or rayDir. Can someone explain to me exactly what Unproject does? I don't think MSDN provides enough info.

Thanks.
Ok, I found this online and made some changes. It makes sense to me now, but I'd appreciate if someone double-checked it:

private IntersectInformation MeshPick(Mesh mesh, float x, float y){               Vector3 v3Near = new Vector3(x, y, 0);               Vector3 v3Far = new Vector3(x, y, 1);                              IntersectInformation closestHit;               v3Near.Unproject(device.Viewport, device.Transform.Projection,                    device.Transform.View, device.Transform.World);               v3Far.Unproject(device.Viewport, device.Transform.Projection,                    device.Transform.View, device.Transform.World);                              Vector3 ray = v3Near-v3Far;                              return mesh.Intersect(v3Near,ray,closestHit) ? closestHit : null; }


[Edited by - yaroslavd on January 17, 2005 5:45:24 PM]

This topic is closed to new replies.

Advertisement