Home > Software design >  When running script on Camera.main play doesn't update scene
When running script on Camera.main play doesn't update scene

Time:02-12

I currently have the following scene that appears in game mode and in my scene mode. enter image description here

I attempt to add some movement with a mouse in a script with the following code:

using UnityEngine;

public class MouseHandler : MonoBehaviour
{
    // horizontal rotation speed
    public float horizontalSpeed = 1f;
    // vertical rotation speed
    public float verticalSpeed = 1f;
    private float xRotation = 0.0f;
    private float yRotation = 0.0f;
    private Camera cam;

    void Start()
    {
        cam = Camera.main;
    }

    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * horizontalSpeed;
        float mouseY = Input.GetAxis("Mouse Y") * verticalSpeed;

        yRotation  = mouseX;
        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90, 90);
// this is for the mouse to move around the scene
        cam.transform.eulerAngles = new Vector3(xRotation, yRotation, 0.0f);
    }
}

It works fine. It's important to note the camera Main Camera displays the image above.
So it looks right.

Here is what the play view looks like when cam.transform.eulerAngles is not commented out. When it's commented out it appears exactly as the first reference which is correct. Any idea what's causing this?

enter image description here

CodePudding user response:

The camera's rotation has some nonzero value assigned in your scene. So, when xRotation and yRotation are initialized with zeros, the offending line cam.transform.eulerAngles = new Vector3(xRotation, yRotation, 0.0f); overwrites the scene-defined rotation with zeros, aka, the "identity rotation".

To avoid this, have your code read what your camera's rotation is at the start and use those values instead of zeros:

void Start()
{
    cam = Camera.main;

    Vector3 camEulers = cam.transform.eulerAngles;
    xRotation = camEulers.x;
    yRotation = camEulers.y;
}

CodePudding user response:

You need to set xRotation and yRotation to the Main Camera initial EulerAngles in the Start() method, because like it is now , in the start method you asign the cam variable to the Camera.Main , and than ( almost immediately ) in the update method you reset its EulerAngles to xRotation and yRotation, which in your case are set to : 0f in their declaration . Try something like this :

void Start() {
    cam = Camera.Main;
    xRotation = <yourInitialXRotationEuler>;
    yRotation = <yourInitialYRotationEuler>;
}
  • Related