- Home /
Mouse-controlled camera getting stuck.
I'm a total noob to unity, and I was trying to get a rudimentary mouse-controlled camera. I have some basic code, and looking horizontally and vertically is fine. However, when I'm looking around the z-rotation of the camera changes, rotating the view weirdly, and when I turn around so the rotation around the y-axis is 180, I can't look horizontally or vertically, it gets locked and if I try to look away it only affects the z-axis rotation, which shouldn't be changed in the first place. Here's my script in the main camera:
var xdirection : float = 0.0;
var ydirection : float = 0.0;
var cenw : float = Screen.Width/2;
var cenh : float = Screen.Height/2;
function Update () {
var mousex : float = Input.GetAxis("Mouse X");
var mousey : float = Input.GetAxis("Mouse Y");
if (mousex != Screen.width/2 && mousey != Screen.height/2) {
xdirection += (mousex*0.4)- cenw*Time.deltaTime;
ydirection -= (mousey*0.4)-cenh*Time.deltaTime;
}
else {
xdirection = 0;
ydirection = 0;
}
xdirection = Mathf.Clamp(xdirection,-90,90);
ydirection = Mathf.Clamp(ydirection,-90,90);
transform.rotation.x = ydirection;
transform.rotation.y = xdirection;
Screen.lockCursor = true;
}
The main camera has a rigidbody and a capsule collider. I've tested it without both components and I get the same issues. "cenw" and "cenh" are the x and y coords for the center of the screen.
Answer by prof · Dec 12, 2013 at 08:42 AM
Rotation in Unity is a Quaternion. For setting rotation directly use quaternion functions. For example
transform.rotataion = Quaternion.Euler(xdir, ydir, transform.rotation.eulerAngles.z);
Your answer
Follow this Question
Related Questions
Camera Relative Movement 2 Answers
How to freeze the rotation or the position on the camera transform? 1 Answer
how do i make first person character rotate left and right along with camera? 0 Answers
Override Oculus Orientation 5.3 1 Answer
How to make the camera rotate only when right click is held down on the mouse? 1 Answer