How to rotate Object with Mouse drag (specifications below)

First of all, I KNOW that this question is already been answered. But what I want to do exactly is rotate an object with mouse…

  • From the Top view (rotation along Y axis only)
  • 3D, not 2D (I’ll use a basic Perspective camera, not Orthographic)
  • Including a “speed” variable that I can have rotation control with it (this one just if it’s possible).
  • C#


**I’ve been trying to adapt other scripts, but I just can’t make it correct. These are four specifications I couldn’t solve and I need together.

Use the values from the mouse axes, Input.GetAxis("Mouse X") and Input.GetAxis("Mouse X"), they will tell you how much the mouse has moved on each axis.

You can then combine these with something like transform.Rotateto make your object rotate on its x&y axes, and I recommend making the rotation relative to world space so its consistent. If you want rotation on the z axis as well then I guess you will need to use another input(There might be a way to do it with the mouse though) like two extra buttons and combine their input with the mouse input.

Speed is simple, just use a speed variable and multiply it by the mouse input, as it is between -1 and 1, if its not just get the sign of the mouse input and multiply by your mouse input.

Hope it helps

Hey! sorry for the delay, was a bit busy.

So what you actually wanted was a ‘look at mouse script’, not simply a way to rotate on an axis with speed. Well the solution might look a but complicated but its actually simple, I hope you will get it.

public float rotationSpeed = 8;  //This will determine max rotation speed, you can adjust in the inspector

    public Camera cam;  //Drag the camera object here

    void Update()
        //If you want to prevent rotation, just don't call this method

    void RotateObject()
         //Get mouse position
        Vector3 mousePos = Input.mousePosition;
       //Adjust mouse z position
       mousePos.z = cam.transform.position.y - transform.position.y;   

       //Get a world position for the mouse
        Vector3 mouseWorldPos = cam.ScreenToWorldPoint(mousePos);   

        //Get the angle to rotate and rotate
        float angle = -Mathf.Atan2(transform.position.z - mouseWorldPos.z, transform.position.x - mouseWorldPos.x) * Mathf.Rad2Deg;

        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, angle, 0), rotationSpeed * Time.deltaTime);

So only one thing to note here is that you probably should let the rotation speed be a bit high, because if its a bit low and the mouse rotates too quickly around the object the object will suddenly switch directions, which doesn’t look natural, anyway it isn’t that much of a problem.

Hope this is what you want :smiley: