Uchiha Madara
Uchiha Madara

Reputation: 1043

Rotate Camera around a gameObject on Mouse drag in Unity

I want to rotate camera around a gameObject (Say a cube) on a drag of my mouse to simulate a feeling that the gameObject is rotating (Just like we rotate object in scene editor and like in shopping websites).

The script below is the one that I'm using. But sometimes the script behaves very weirdly. The camera rotates in the opposite direction than the anticipated direction. Why is this happening? What changes do I need to make in the code to make it work? Please help.

using UnityEngine;
using System.Collections;

public class ExampleBehaviourScript : MonoBehaviour
{
    public Camera cameraObj;
    public GameObject myGameObj;
    public float speed = 2f;

    void Update()
    {
        RotateCamera();
    }

    void RotateCamera()
    {
        if(Input.GetMouseButton(0))
        {
         cameraObj.transform.RotateAround(myGameObj.transform.position, 
                                         Vector3.up,
                                         -Input.GetAxis("Mouse X")*speed);

         cameraObj.transform.RotateAround(myGameObj.transform.position, 
                                         Vector3.right,
                                         -Input.GetAxis("Mouse Y")*speed);
        } 

    }
}

Upvotes: 2

Views: 17879

Answers (3)

Victor HHT
Victor HHT

Reputation: 31

My solution to rotate the camera in Unity with Mouse or Touch

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class CameraRotator : MonoBehaviour
{
    public Transform target;
    public Camera mainCamera;
    [Range(0.1f, 5f)]
    [Tooltip("How sensitive the mouse drag to camera rotation")]
    public float mouseRotateSpeed = 0.8f;
    [Range(0.01f, 100)]
    [Tooltip("How sensitive the touch drag to camera rotation")]
    public float touchRotateSpeed = 17.5f;
    [Tooltip("Smaller positive value means smoother rotation, 1 means no smooth apply")]
    public float slerpValue = 0.25f; 
    public enum RotateMethod { Mouse, Touch };
    [Tooltip("How do you like to rotate the camera")]
    public RotateMethod rotateMethod = RotateMethod.Mouse;


    private Vector2 swipeDirection; //swipe delta vector2
    private Quaternion cameraRot; // store the quaternion after the slerp operation
    private Touch touch;
    private float distanceBetweenCameraAndTarget;

    private float minXRotAngle = -80; //min angle around x axis
    private float maxXRotAngle  = 80; // max angle around x axis

    //Mouse rotation related
    private float rotX; // around x
    private float rotY; // around y
    private void Awake()
    {
        if (mainCamera == null)
        {
            mainCamera = Camera.main;
        }

        
    }
    // Start is called before the first frame update
    void Start()
    {
        distanceBetweenCameraAndTarget = Vector3.Distance(mainCamera.transform.position, target.position);
    }

    // Update is called once per frame
    void Update()
    {
        if (rotateMethod == RotateMethod.Mouse)
        {
            if (Input.GetMouseButton(0))
            {
                rotX += -Input.GetAxis("Mouse Y") * mouseRotateSpeed; // around X
                rotY += Input.GetAxis("Mouse X") * mouseRotateSpeed;
            }

            if (rotX < minXRotAngle)
            {
                rotX = minXRotAngle;
            }
            else if (rotX > maxXRotAngle)
            {
                rotX = maxXRotAngle;
            }
        }
        else if (rotateMethod == RotateMethod.Touch)
        {
            if (Input.touchCount > 0)
            {
                touch = Input.GetTouch(0);
                if (touch.phase == TouchPhase.Began)
                {
                    //Debug.Log("Touch Began");

                }
                else if (touch.phase == TouchPhase.Moved)
                {
                    swipeDirection += touch.deltaPosition * Time.deltaTime * touchRotateSpeed;
                }
                else if (touch.phase == TouchPhase.Ended)
                {
                    //Debug.Log("Touch Ended");
                }
            }

            if (swipeDirection.y < minXRotAngle)
            {
                swipeDirection.y = minXRotAngle;
            }
            else if (swipeDirection.y > maxXRotAngle)
            {
                swipeDirection.y = maxXRotAngle;
            }
        }

    }

    private void LateUpdate()
    {

        Vector3 dir = new Vector3(0, 0, -distanceBetweenCameraAndTarget); //assign value to the distance between the maincamera and the target

        Quaternion newQ; // value equal to the delta change of our mouse or touch position
        if (rotateMethod == RotateMethod.Mouse)
        {
           newQ  = Quaternion.Euler(rotX , rotY, 0); //We are setting the rotation around X, Y, Z axis respectively
        }
        else
        {
            newQ = Quaternion.Euler(swipeDirection.y , -swipeDirection.x, 0);
        }
        cameraRot = Quaternion.Slerp(cameraRot, newQ, slerpValue);  //let cameraRot value gradually reach newQ which corresponds to our touch
        mainCamera.transform.position = target.position + cameraRot * dir;
        mainCamera.transform.LookAt(target.position);

    }

    public void SetCamPos()
    {
        if(mainCamera == null)
        {
            mainCamera = Camera.main;
        }
        mainCamera.transform.position = new Vector3(0, 0, -distanceBetweenCameraAndTarget);
    }

}

Upvotes: 3

Ahad Javed
Ahad Javed

Reputation: 1

To move your cube in the direction of mouse moves change your code like blow:

void RotateCamera()
{
    if (Input.GetMouseButton(0))
    {
        cameraObj.transform.RotateAround(myGameObj.transform.position,
                                        Vector3.up,
                                        Input.GetAxis("Mouse X") * speed);

        cameraObj.transform.RotateAround(myGameObj.transform.position,
                                        Vector3.right,
                                        -Input.GetAxis("Mouse Y") * speed);
    }

}

Upvotes: -2

Heejae Kim
Heejae Kim

Reputation: 539

I think it is caused by the reference axis.

Because you used Vector3.up, Vector3.right, not the camera's one, it wasn't rotated the anticipated direction. So, you should change like below.

void RotateCamera()
{
    if(Input.GetMouseButton(0))
    {
     cameraObj.transform.RotateAround(myGameObj.transform.position, 
                                     cameraObj.transform.up,
                                     -Input.GetAxis("Mouse X")*speed);

     cameraObj.transform.RotateAround(myGameObj.transform.position, 
                                     cameraObj.transform.right,
                                     -Input.GetAxis("Mouse Y")*speed);
    } 

}

Upvotes: 4

Related Questions