How to make camera rotation unity?

In this article, We will look at how to make camera rotation unity which also works on touch devices like android and iPhones.

Many times we face issues while rotating the camera, Which works on PC or Unity Editor But does not on android devices.

You may have faced this kind of issue, So today in this article you are going to get your solution.

Camera rotation unity

camera rotation unity
camera rotation unity

You may be wondering, Will this script work on touch devices like android?

Yes, of course, The script that I am going to share with you also works on touch devices.

Let’s take a look at the very simple script for it.

using UnityEngine;

public class CameraRotaion: MonoBehaviour
{

    private Vector3 firstpoint; 
    private Vector3 secondpoint;

    private float xAngle; 
    private float yAngle;
    private float xAngTemp;
    private float yAngTemp;

    // Booleans
    private bool isUpdatePosition = false;

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            OnStartTouch();
            isUpdatePosition = true;
        }

        if(Input.GetMouseButtonUp(0))
        {
            isUpdatePosition = false;
        }
        
        if(isUpdatePosition)
        {
            UpdatePosition();
        }
    }

    private void OnStartTouch()
    {
        firstpoint = Input.mousePosition;

        xAngTemp = xAngle;
        yAngTemp = yAngle;
    }

    public void UpdatePosition()
    {
        secondpoint = Input.mousePosition;

        xAngle = xAngTemp + (secondpoint.x - firstpoint.x) * 180.0f / Screen.width;
        yAngle = yAngTemp - (secondpoint.y - firstpoint.y) * 90.0f / Screen.height;

        transform.rotation = Quaternion.Euler(yAngle, xAngle, 0.0f);
    }
}

This is the very simple script of camera rotation that works on any device as Android or PC builds in unity.

Note:– Both Input.GetMouseButtonDown and Input.GetMouseButtonUp works on touch devices.

Let’s breakdown the above script

  • Detect the Start Touch and End Touch using Input.GetMouseButtonDown and Input.GetMouseButtonUp.
  • Then we hold the previous angles in tempAngles to prevent the jerk issues in Touch devices while rotating the camera in unity.
  • Lastly, we assign the final angles that are, angle = last angle + currentRotateDetected
  • Finally, we assign these values to our transforms rotation.

This is how to make camera rotation unity, You can also limit or clamp the camera rotation if you want to.

Hope this article was helpful. Let me know In the comment section if you have any questions or queries.

Leave a Comment

Your email address will not be published.