1
votes

I am pulling my hair out over this mouse picking thing. I do not know if the problem lies in my Ray calculation or my BoundingSpheres, anyway here's the code for my ray calculations:

public Ray CalculateRay(InputManager input)  
{   
    Vector3 nearSource = new Vector3(input.CurrentMousePosition, 0f);  
    Vector3 farSource = new Vector3(input.CurrentMousePosition, 1f);  

    Vector3 nearPoint = Engine.Device.Viewport.Unproject(nearSource, _projectionMatrix,
    _viewMatrix, Matrix.Identity);

    Vector3 farPoint = Engine.Device.Viewport.Unproject(farSource,
    _projectionMatrix, _viewMatrix, Matrix.Identity); 

    Vector3 direction = farPoint - nearPoint;
    direction.Normalize();

    return new Ray(nearPoint, direction);
}

and for the intersection check:

public bool RayIntersectsModel()
{           
    foreach (ModelMesh mesh in _model.Meshes)
    {
        BoundingSphere sphere = mesh.BoundingSphere;  

        sphere.Center = _position; 

        Ray ray = Engine.Camera.CalculateRay(Engine.Input);

        if (sphere.Intersects(ray) != null) 
        {
           return true;
        }  
    }
    return false;
}

It's not like it isn't working at all but it seems to be very inaccurate... or something. The models are just spheres, very simple. Any help or insight would be greatly appreciated! Thanks!

1
What values does your cameraPosition, sphere center, and have radius have? If the sphere is far enough away from the camera (like many places to the left of the decimal), then floating point in-accuracy while setting up the ray direction could come into play. If you think this may be applicable, try to use 10 as the Z value of the farSourse to give the Ray a better chance (like aiming a gun with a long rifle barrel instead of a short pistol barrel). - Steve H

1 Answers

0
votes

Well, when I was transforming my bounding sphere I was first applying the world matrix then the bone transforms. This seems to put the bounding sphere in the wrong place. Switching it to first applying the bone transforms THEN the world matrix did it.