Problems with Mouse.SetPosition

Hello,

I am making a game where camera rotation changes on mouse input. The logic is this:

  1. On every tick measure the difference between the mouse position and center of the screen,
  2. Change the rotation of the camera depending on the difference,
  3. Reset the mouse position to the center of the screen.

Here is the method which updates my camera:

    private void HandleCamera(Camera camera, GraphicsDeviceManager graphics)
    {
        float xAmount = newMouseState.X - graphics.PreferredBackBufferWidth / 2;
        camera.cameraRotation.Y -= xAmount * mouseSensitivity;
        Mouse.SetPosition(graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight / 2);
    }

In general, this works well, and moving the mouse changes the rotation of the camera as expected, but the input is very choppy. As far as I can tell, everything works smoothly until I add in this bit, which resets the position of the camera:

Mouse.SetPosition(graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight / 2);

Once this is added, the camera rotates very smoothly at times, but at times it gets very choppy, to the point when it’s hard to move it at all. If you have any ideas on what I may be doing wrong, please let me know! ;_;

PS: I should probably add that the HandleCamera method is called from the main Update method in the game, so the position of the mouse is being reset at a very high rate.

Why don’t you cache the value of graphics.PreferredBackBufferWidth / 2 and height as it won’t change every frame.

Is camera.cameraRotation.Y reset somewhere ? Maybe you reach a glimbal lock pretty fast ?
Maybe you should take time into account between updates, rather than update calls which is hardware related if it runs at max speed (fixedtimestep)
Are you trying to make a view rotation around Y ?

1 Like

Alkher, I bow down before the glory of your magnificence.

Maybe you should take time into account between updates, rather than
update calls which is hardware related if it runs at max speed
(fixedtimestep)

This is exactly what did the trick! I wasn’t aware of a feature like this before, but I added:

            IsFixedTimeStep = true;
            TargetElapsedTime = TimeSpan.FromMilliseconds(16);

In my game constructor to set the update rate to just above 60 times a second, and the camera movement is smooth as butter now.

Just in case anyone has a problem like this in the future, this post was very informative: Time Steps - RB Whitaker's Wiki

Once again thanks Alkher, you are my Messiah.