In this code example:
Get a Ray in 3D:
Ray GetPickRay()
{
MouseState mouseState = Mouse.GetState();
int mouseX = mouseState.X;
int mouseY = mouseState.Y;
Vector3 nearsource = new Vector3((float)mouseX, (float)mouseY, 0f);
Vector3 farsource = new Vector3((float)mouseX, (float)mouseY, 1f);
Matrix world = Matrix.CreateTranslation(0, 0, 0);
Vector3 nearPoint = GraphicsDevice.Viewport.Unproject(nearsource,
camera.Projection, camera.View, world);
Vector3 farPoint = GraphicsDevice.Viewport.Unproject(farsource,
camera.Projection, camera.View, world);
Vector3 direction = farPoint - nearPoint;
direction.Normalize();
Ray pickRay = new Ray(nearPoint, direction);
return pickRay;
}
And use that Ray to check collision:
public void CheckMouse()
{
MouseState mouseState = Mouse.GetState();
float deltaX = (float)mouseState.X - (float)lastMouseState2.X;
float deltaY = -(float)mouseState.Y + (float)lastMouseState2.Y;
if (mouseState.LeftButton==ButtonState.Pressed)
{
Ray ray = GetPickRay();
float selectedDistance = float.MaxValue;
Nullable<float> result = ray.Intersects(models[0].BoudingSphere);
if (result.HasValue==true)
{
if (result.Value < selectedDistance)
{
models[0].Positon += new Vector3(deltaX, deltaY, 0);
}
}
}
lastMouseState2 = mouseState;
}</pre>
And you can drag and drop one model by mouse.