Question

I am trying to make a 3D game using Visual C# Express 2010. I am using XNA 4.0 in this software.

In this game, you have to be able to look left, right, up, and down using the mouse. (1st Person view, I just want to rotate the camera)

As long as the game is running, like Minecraft I want the mouse to stay in the window, and only when the esc key is pressed, does the mouse become visible.

Can anyone tell me the correct commands to track mouse motion, and to keep the mouse in the window, or point me toward a good tutorial for this?

Was it helpful?

Solution

OK, I've got some information for you. You can use Mouse.SetPosition method to keep the cursor within the bounds of the window. Just be sure to only call that when the window is in focus and not minimized. Also keep in mind that the position is relative to the top-left corner of the window.

Now for the movement, that is simply comparing the current mouse state with the center of the window. Then you'd need to call SetPosition to put the cursor back in the center of the window. So something like this:

void Update()
{
    Rectangle center = this.Window.ClientBounds;
    MouseState newState = Mouse.GetState();
    double angle = Math.Atan2(newState.Y - center.Y, newState.X - center.X);
    // Change camera angle. Needs to be tuned to your wants most likely.
    Mouse.SetPosition((int)center.X, (int)center.Y);
}

On a side note, there is a more dedicated version of this website: gamedev.stackexchange.com. Also, I must put in a disclaimer, this was a learning experience for me and unfortunately I lack the time to test the above code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top