Ray intersect issues.

Hi,

I’m trying to pick blocks in my voxel block engine I’ve created in monogame. I’m attempting to use the following code:

float x = (float)mouse.X;
float y = (float)mouse.Y;

Vector3 nearPosition = this.GraphicsDevice.Viewport.Unproject(new Vector3(x, y, 0f), Engine.EosStatic.CurrentCamera.mProjection, Engine.EosStatic.CurrentCamera.mView, Matrix.Identity);
Vector3 farPosition = this.GraphicsDevice.Viewport.Unproject(new Vector3(x, y, 1f), Engine.EosStatic.CurrentCamera.mProjection, Engine.EosStatic.CurrentCamera.mView, Matrix.Identity);

Vector3 Direction = farPosition - nearPosition;
Direction.Normalize();
Ray ray = new Ray(nearPosition, Direction);

foreach (Voxel.Block block in Blocks)
{
if (!block.Exists)
continue;

float? value = ray.Intersects(block.Bounds);
if (value.HasValue)
{
value = Math.Abs((float)value);
blocks.Add(block, value);
}
}

return blocks;
}

Sometimes I pick the correct block other times my ray goes right through the block it should pick and picks one along the ray later on. I make sure to pick the closest block that intersects with the ray. I generate my view matrix with: “Matrix.CreateLookAt”, and my projection matrix with: “Matrix.CreatePerspectiveFieldOfView”. I know my camera code looks good as I can see and move around my world. Anyone have any ideas on this one? Thanks for any help!

I figured this out! I needed to traverse through ALL of my chunks that were intersected. I was just grabbing the closest intersected chunk before which caused issues.

Hope this helps anyone else! :smile:

-Toaster