Mouse Look and Screen.lockCursor

The problem is simple, I want a mouse look. I have coded these for years. One would think it’d be easy:

Screen.lockCursor = true;
Vector3 mouseOffset = Input.mousePosition - new Vector3(Screen.width / 2f, Screen.height / 2f, 0f);
camera.transform.Rotate(new Vector3(mouseOffset.y, mouseOffset.x, 0f), Space.Self);

That’s all it should take. But, the Y difference is always off by 16 pixels. Also, the X difference rarely goes beyond 0, no matter how fast I move my mouse. Clearly, Screen.lockCursor isn’t at the actual center screen, as advertised. It is doing something else completely.

Why doesn’t it work?

(Spending an hour trying to make three lines of code work and 20 minutes having unityAnswers site refuse to log me in, on top of that, it is eating up my lunch time. This makes me one unhappy camper.)

Vector3 mouseOffset = new Vector3(-Input.GetAxis(“Mouse Y”), Input.GetAxis(“Mouse X”), 0f);
camera.transform.Rotate(mouseOffset, Space.Self);
//auto-up the lazy way:
camera.transform.LookAt(camera.transform.position + camera.transform.forward, Vector3.up);

There. I win.

Thanks David for showing me the GetAxis(“Mouse X”) and Y. You have saved many soft cuddly things from certain doom.

Screen.lockCursor is a bit glitchy in both WebPlayer and the Unity Editor itself but it kinda works in StandAlone version. I would suggest writing a bit more advanced mouselook script to make it less buggy.

private var xtargetRotation : float=10;

private var ytargetRotation : float=10;

var xSensitivity : float=7;
var ySensitivity : float=6;

var min = -60;
var max = 60;

var smoothing = 1;

function LateUpdate()
var yAxisMove : float = Input.GetAxis(“Mouse Y”) * ySensitivity;
ytargetRotation += -yAxisMove;
ytargetRotation = ytargetRotation % 360;
ytargetRotation = Mathf.Clamp(ytargetRotation,min,max);

var xAxisMove : float = Input.GetAxis("Mouse X")*xSensitivity;
xtargetRotation += xAxisMove;
xtargetRotation = xtargetRotation % 360;

transform.localRotation = Quaternion.Lerp(transform.localRotation, 
											Time.deltaTime*10 / smoothing);

transform.parent.rotation = Quaternion.Lerp(transform.parent.rotation, 
											Time.deltaTime*10 / smoothing);


This one is mine and it works like a real head. The body rotates just in the Y axis and camera in the X one. But if you wan’t it as one object then change the code where i set the rotation. To set it up just make a player, parent a camera to it and just add this to the camera.

– David