# Managed DirectX ray picking

## Recommended Posts

d4g4m3r    100
Judging from posts on ZBuffer, this is a pretty common problem, but I haven't been able to find any help for it. I'm working on a haptic project, involving a very simple driving simulator. I've got a "car" mesh on an oval road surrounded by a "wall" mesh object, and want to detect how close I am to the closest point on the wall. In the way my simulation is set up, the car actually stays stationary and the "wall" moves around the car. Here are the transforms I use to set up the world:
device.Transform.World =
Matrix.RotationY((float)Math.PI / 2) * Matrix.RotationX((float)Math.PI / 2)
* Matrix.Translation(-(float)carmeshposition.X, -(float)carmeshposition.Y, -(float)carmeshposition.Z)
* Matrix.RotationYawPitchRoll((float)carmeshangles.X, (float)carmeshangles.Y, (float)carmeshangles.Z);

DrawMesh(wallmesh, wallmaterials, walltextures);

device.Transform.World = Matrix.Scaling(scaling, scaling, scaling) *Matrix.RotationY((float)Math.PI / 2) * Matrix.RotationX((float)Math.PI / 2);
DrawMesh(carmesh, carmeshmaterials, carmeshtextures);
I have a car-center Vector and a car-radius float. I'm trying to find the easiest, quickest, dirtiest method I can for finding how close the car is to the wall. So, right now I'm trying to use Mesh.Intersect to do ray-picking from the car center to the wall mesh, thusly:
wallmesh.Intersect(carcenter, new Vector3(0, 0, (float)(i * Math.PI / 180)), out intersectionInfo);
for 360 degrees around the Z-axis, and storing the distance from the intersectionInfo object into a global double, comparing against the current closest distance as I go to get the smallest distance. Unfortunately, I haven't gotten this working. Am I using the direction ray parameter wrong in the Intersect function, or do I need to somehow do a world transformation on the ray, or both, or neither? Is there an easier way to do this kind of point-to-mesh collision detection? edit: To avoid confusion, "carposition" is a position vector that changes as the car drives around and whose function is to move the wall mesh, while "carcenter" is determined during initialization of the car mesh and never changes.

##### Share on other sites
remigius    1172

As I recall Mesh.Intersect requires the ray (so origin and direction) to be in the model space of the mesh. It looks like your carcenter and ray direction are actually world space coordinates, so if that's correct you'd want to transform them with the inverse of the world matrix you use for wallmesh. I think MDX supports Matrix.Invert and Vector3.Transform to do this.