[Solved] Spin a 3D object using mouse

Hey all,

I’m trying to get a simple single-axis object spin/rotation going using the mouse. In short, dragging the mouse to the left spins the object smoothly clockwise and vice versa.

The code below works well when the mouse moves really slowly, but the spinning goes back-and-forth instead of a single direction when you drag across the screen quickly.

I’m guessing this has to do with the Lerp and handling of rotations going below 0 or above 359, but I’ve not found a solution yet.

Any ideas? Cheers

using UnityEngine;
using System.Collections;

public class TownInput : MonoBehaviour
{
    public GameObject spinObject;
    private float panOrigin;
    private float ySpinDegree;

    void Update()
    {
        // Left click
        if (Input.GetMouseButtonDown(0))
        {
            panOrigin = Input.mousePosition.x;
        }

        // Get mouse drag distance for spin
        if (Input.GetMouseButton(0))
        {
            ySpinDegree += (Input.mousePosition.x - panOrigin);
            panOrigin = Input.mousePosition.x;    //reset origin pos
            Debug.Log(ySpinDegree);
        }

       // Spin it!
       Quaternion fromRotation = spinObject.transform.rotation;
       Quaternion toRotation = Quaternion.Euler(0f, -ySpinDegree, 0f);
       spinObject.transform.rotation = Quaternion.Lerp(fromRotation, toRotation, Time.deltaTime * 0.8f);
   }
}

Solved! Found the solution from this post:

Basically use Lerp on a rotation variable instead of the Quaternion.

currentDegree = Mathf.Lerp(currentDegree, ySpinDegree, Time.deltaTime * 0.8f);
spinObject.transform.rotation = Quaternion.Euler(0f, -currentDegree, 0f);