JS Rotating an object by dragging OnMouseOver

I have a game object, say a cube, and I would like it to rotate when the mouse is dragged across it, but once the mouse moves of the object wont cause it to rotate any more and the object will spin with inertia till it stops.

var rotationSpeed = 10.0;
var lerpSpeed = 1.0;

private var speed = new Vector3();
private var avgSpeed = new Vector3();
private var dragging = false;
private var targetSpeedX = new Vector3();

function OnMouseEnter() 
{
    dragging = true;
}

function Update () 
{

    if (dragging) {
        speed = new Vector3(-Input.GetAxis ("Mouse X"), Input.GetAxis("Mouse Y"), 0);
        avgSpeed = Vector3.Lerp(avgSpeed,speed,Time.deltaTime * 5);
    } else {
        if (dragging) {
            speed = avgSpeed;
            dragging = false;
        }
        var i = Time.deltaTime * lerpSpeed;
        speed = Vector3.Lerp( speed, Vector3.zero, i);   
    }

    transform.Rotate(Vector3.up, speed.x * rotationSpeed, Space.World);

}

This is what I have so far.

The problem is the mouse movement after it moves off the game object causes the object to rotate still.

I have have a feeling it’s down to me not using OnMouseOver correctly, would OnMouseEnter be better.

Any help and corrections would be greatly appreciated.

your issue lies in the “onmouseenter” function.

dragging gets set to true, but does not get set to false again.

You could add a “onmouseexit” function where your variable gets set to false:
http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.OnMouseExit.html

hope its useful

  • Kacer