Home > Net >  Camera resets keyboard rotation before applying mouse rotation
Camera resets keyboard rotation before applying mouse rotation

Time:11-10

I'm having an issue with the free roam camera I'm trying to implement. The camera can be rotated via keyboard (only on the Y axis) and via mouse (on the X and Y axis) while holding the middle mouse button. With my current implementation, if I rotate the camera using the keyboard and the rotate it using the mouse, it remove any rotation done by the keyboard as soon as I hit the middle mouse button. Of course I would like to not do that... Code is below. Can someone give tell me what I'm doing wrong?

private void RotateCameraKeyboard()
    {
        if (Input.GetKey(KeyCode.Q))
        {
            transform.RotateAround(transform.position, Vector3.up, -rotationSpeed * Time.deltaTime * 30);
        }

        if (Input.GetKey(KeyCode.E))
        {
            transform.RotateAround(transform.position, Vector3.up, rotationSpeed * Time.deltaTime * 30);
        }
    }

private void RotateCameraMouse()
    {
        if (Input.GetMouseButton(2))
        {
            pitch -= rotationSpeed * Input.GetAxis("Mouse Y");
            yaw  = rotationSpeed * Input.GetAxis("Mouse X");

            pitch = Mathf.Clamp(pitch, -90f, 90f);

            while (yaw < 0f)
            {
                yaw  = 360f;
            }

            while (yaw >= 360f)
            {
                yaw -= 360f;
            }

            transform.eulerAngles = new Vector3(pitch, yaw, 0f);
        }
    }

CodePudding user response:

Instead of using RotateAround (which in your case of using the transform.position as pivot is redundant anyway .. you could as well just use Rotate) additionally also add the according amount to your pitch and yawn.

I would simply generalize and use the same method for both inputs like e.g.

private void RotateCameraKeyboard()
{
    if (Input.GetKey(KeyCode.Q))
    {
        Rotate(-rotationSpeed * Time.deltaTime * 30, 0);
    }

    if (Input.GetKey(KeyCode.E))
    {
        Rotate(rotationSpeed * Time.deltaTime * 30, 0);
    }
}

private void RotateCameraMouse()
{
    if (Input.GetMouseButton(2))
    {
        var pitchChange = rotationSpeed * Input.GetAxis("Mouse Y");
        var yawChange = rotationSpeed * Input.GetAxis("Mouse X");

        Rotate(yawChange, pitchChange);
    }
}

private void Rotate(float yawChange, float pitchChange)
{
    pitch = Mathf.Clamp(pitch   pitchChange, -90f, 90f);

    yaw  = yawChange;

    while (yaw < 0f)
    {
        yaw  = 360f;
    }

    while (yaw >= 360f)
    {
        yaw -= 360f;
    }

    transform.eulerAngles = new Vector3(pitch, yaw, 0f);
}
  • Related