Weird camera controller behaviour

I have a strange problem with my camera controller and I can’t understand why. When I look in certain directions, the camera starts to shake. The rotation of the camera seems to change very quickly at this moment, but I don’t understand why.

Here is the code I use (this is called in update).

void PhotoMode()
    {
        Vector3 newPos = transform.position;
        //déplacement avant
        if(Input.GetKey(InputManager.IM.forward))
        {
            newPos += cam.transform.forward  * moveSpeedPhoto * Time.unscaledDeltaTime;
        }

        //déplacement arrière
        if(Input.GetKey(InputManager.IM.backward))
        {
            newPos -= cam.transform.forward * moveSpeedPhoto * Time.unscaledDeltaTime;
        }

        //déplacement gauche
        if(Input.GetKey(InputManager.IM.left))
        {
            newPos += -transform.right * moveSpeedPhoto * Time.unscaledDeltaTime;
        }

        //déplacement droite
        if(Input.GetKey(InputManager.IM.right))
        {  
            newPos += transform.right * moveSpeedPhoto * Time.unscaledDeltaTime;
        }

        float x = Input.GetAxis("Mouse X");
        float y = Input.GetAxis("Mouse Y");

        x *= photoRotSpeed * Time.unscaledDeltaTime;
        y *= photoRotSpeed * Time.unscaledDeltaTime;

        currentX = Mathf.Lerp(currentX, x, smoothTime * Time.unscaledDeltaTime);
        currentY = Mathf.Lerp(currentY, y, smoothTime * Time.unscaledDeltaTime);

        float rotationX = transform.localEulerAngles.y + currentX * photoRotSpeed;

        rotationY += currentY * photoRotSpeed;
        rotationY = Mathf.Clamp(rotationY, -90+65, 90+65);

        transform.localRotation = Quaternion.Euler(new Vector3(-rotationY, rotationX, 0));

        transform.position = newPos;
    }

6958343--819323--Bug.gif

Based on your Y rotation being near 180 degrees, it’s probably gimbal lock.

Camera code can get quite tricky.

Have you considered just installing the Cinemachine package and using that for your camera control?

2 Likes

I would still like to understand why it does this… It’s such a simple code.

Fair enough…

I’m going to guess that your problem begins with reading from .localEulerAngles (or .eulerAngles), and you can use Debug.Log() and prove me correct or wrong.

Neither such property should be read from on an ongoing basis. They may be used in certain circumstances when you are sure the rotation involved is otherwise “clean,” such as in Start() or perhaps when only rotated on a single axis.

Once you start combining axes of rotation, reading from .eulerAngles is a strict no-no.

1 Like

Okay thanks a lot, I will try that !