Search code examples
unity-game-enginerotationunityscript

Rotate camera on z-axis using keyboard


I'm coming across a roadblock on something I thought would be a relatively simple problem. I want to "roll" the camera on the z-axis by pressing the "Q" and "E" keys.

Here is the code I've written, which is attached to my camera object:

#pragma strict

var keyboardSensitivity : float = 10.0f;
private var rotZ : float;
private var localRotation : Quaternion;

function Start () {
    rotZ = 0.0f;
}

function Update () {
    if(Input.GetKey(KeyCode.Q)) {
        rotZ += Time.deltaTime * keyboardSensitivity;
        localRotation = Quaternion.Euler(0.0f, 0.0f, rotZ);
        transform.rotation = localRotation;
    }
    if(Input.GetKey(KeyCode.E)) {
        rotZ -= Time.deltaTime * keyboardSensitivity;
        localRotation = Quaternion.Euler(0.0f, 0.0f, rotZ);
        transform.rotation = localRotation;
    } 
}

Based on my knowledge, this should be all that is needed. But when I hit the Q or E keys, absolutely nothing happens. Why?


Solution

  • Nothing happens because your code is likely not attached to the camera or it is attached to another GameObject. It cannot be attached to another GameObject. It has to be attached to the camera since you are referencing transform.rotation which will affect the current GameObject the script is attached to.

    Select your camera then drag the script to it. Click "Play" and press the Q or E button. The camera should rotate. I really do recommend Unity project tutorials to you.