Locking the Cursor at the center.

I've been looking at answers, and I don't understand them. All I want is a script that will lock the cursor at the center of the screen for a stand-alone game. Just one script, NOTHING ELSE.

Hello.

I needed what you want during a testing proyect. I used "Screen.lockCursor" to block the cursor in the center of screen to simulate the pointer of a gun.

Here you have the API example: ScreenLookCursor

I hope its what you want. See you.

void Update()
{
if (Input.GetKey(KeyCode.Escape))
Screen.lockCursor = false;
else
Screen.lockCursor = true;
}

Press and hold escape to unlock the mouse.

Every thing below this line!

public float mouseSensitivity = 100.0f;
public float clampAngle = 80.0f;

private float rotY = 0.0f; // rotation around the up/y axis
private float rotX = 0.0f; // rotation around the right/x axis

void Start ()
{
	Vector3 rot = transform.localRotation.eulerAngles;
	rotY = rot.y;
	rotX = rot.x;
}

void Update ()
{

	if (Input.GetKey(KeyCode.Escape))
		Screen.lockCursor = false;
	else
		Screen.lockCursor = true;
	
	float mouseX = Input.GetAxis("Mouse X");
	float mouseY = -Input.GetAxis("Mouse Y");

	rotY += mouseX * mouseSensitivity * Time.deltaTime;
	rotX += mouseY * mouseSensitivity * Time.deltaTime;

	rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);

	Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
	transform.rotation = localRotation;
}

I’ve been looking at threads about this problem and haven’t found an easy enough answer, so I thought I’d add my two cents:

It’s not a perfect solution bot for prototyping purposes I use this:

function Update () {
    Screen.lockCursor = true;
    Screen.lockCursor = false;
}

Screen.lockCursor moves the pointer to the center of the screen, so it does almost exactly what the OP suggested - resets the cursor every frame.

You could also use a MouseMove event for example :slight_smile:

Not very clean but it does the job, you retain OnMouseDown functionality, the cursor remains visible.