简体   繁体   中英

Camera will not rotate using scripts in Unity3d

 if (Input.GetKeyDown(KeyCode.E))
    {
        Camera.main.transform.eulerAngles = new Vector3(0, 180, 0);
    }

This code should rotate the camera so it is facing behind the player. It is meant to be a "look back" feature of sorts. The problem is, is that it doesn't. It just freaks out and snaps back to its original orientation. Why is this?

You are not rotating the GameObject when you press the 'E' key. You're instead setting the rotation of the camera to the-same 180 value when 'E' key is pressed. It will always be 180 each time the key is pressed.

If you want to rotate the camera 180 deg each time the 'E' key is pressed, you have to increment the camera rotation with += instead of just = which simply assigns the angle with 180 deg over and over again:

void Update()
{
    if (Input.GetKeyDown(KeyCode.E))
    {
        Camera.main.transform.eulerAngles += new Vector3(0, 180, 0);
    }
}

You can also use transform.Rotate :

void Update()
{
    if (Input.GetKeyDown(KeyCode.E))
    {
        Camera.main.transform.Rotate(new Vector3(0, 180, 0));
    }
}

Notice how I used the Update function became FixedUpdate is used to add physics force to Rigidbody Objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM