0
votes

It doesn't work

using System.Runtime.InteropServices; //for mouse reset
int mouseXPos = 960; //half of 1920
int mouseYPos = 540; //half of 1080
[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);
SetCursorPos(mouseXPos, mouseYPos);//Call this when you want to set the mouse position

in FixedUpdate:

mousePos = Input.mousePosition;
mousePos.z = turnSpeed;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
transform.LookAt(mousePos);

mousePos.z is how far from the camera the target is that the camera looks at. the mouse should be put in the middle of the screen, but when when the program is built and in the editor (i have to offset the mouseXPos and mouseYPos to work with the fullscreen play window) the mouse doesn't get set to the very centre, and so there is drift, and the view slowly moves up. it seems to be off by 2.3 pixels and when i make a big mouse movement, it doesn't go back to zero, it is off by 0.1 or 0.2 pixels

example video: https://imgur.com/a/hPFkGjE In the log you can see the vector3 should be 0,0,5. I disabled the rotation for the video.

1

1 Answers

0
votes

You really shouldn't be using System libraries to control user input, especially in Unity. Use the Cursor.lockState and Cursor.visible properties to control the cursor. In particular, it seems like what you want to do is lcok the cursor to the centre of the screen. This can be done with the following:

/**
 * Locks the cursor to the centre of the game window.
 */
private void LockCursor()
{
    Cursor.lockState = CursorLockMode.Locked;
}

// ...
// In some MonoBehaviour...
private void Start()
{
    LockCursor();
}

Refer to the documentation for more info.