- Home /
Rotate object using mouse, slows down on release
Hi, I'm working on a script so that a sphere will rotate relative to the position of the mouse click and once released will continue spinning but will slow down over time. I have got the sphere rotating on mouse drag so far but I wouldn't know where to begin for the second part. Here is my code:
using UnityEngine;
using System.Collections;
public class globeRotate : MonoBehaviour
{
private float rotationSpeed = 15.0F;
private bool dragging = false;
private GameObject runningBoyObject;
private playerRotate myScript;
void Start()
{
runningBoyObject = GameObject.Find("Villager");
myScript = runningBoyObject.GetComponent<playerRotate>();
}
void FixedUpdate()
{
if(myScript.animation.isPlaying == false)
myScript.animation.CrossFade("Idle");
}
void OnMouseDown()
{
dragging = true;
}
void OnMouseDrag()
{
transform.Rotate((Input.GetAxis("Mouse Y")*rotationSpeed*Time.deltaTime),0,(-Input.GetAxis("Mouse X")*rotationSpeed*Time.deltaTime),Space.World);
myScript.animation.CrossFade("Start_To_Jog");
}
void OnMouseUp()
{
if(dragging)
{
dragging = false;
myScript.animation.CrossFade("Jog_To_Stop");
}
}
}
Answer by Joyrider · Aug 12, 2013 at 06:21 PM
Okay, that is called inertia. What you want to do is
1/ save the speed your sphere is rotating at just before letting go of the mouse button. My guess would be to always save your rotation value in OnMouseDrag.
myLastKnownSpeed = new Vector3(Input.GetAxis("Mouse Y")*rotationSpeed*Time.deltaTime,0,(-Input.GetAxis("Mouse X")*rotationSpeed*Time.deltaTime));
2/ And once you release the mouse button, (either in update or in a coroutine) substract a value from that speed every frame.
myLastKnownSpeed -= inertialDamp *
Time.deltaTime * myLastKnownSpeed;
or any other mathematical calculation that will get you the result you want.
3/ Continue to apply the rotation speed calculated at every frame speed until your speed drops under a given value
if(myLastKnownSpeed.Magnitude < 0.1f)
myLastKnownSpeed = Vector3.zero;
transform.Rotate(myLastKnownSpeed);
Answer by AlexClarke117 · Sep 03, 2013 at 01:10 AM
Just to let you know this is what worked pretty much, here is the code snippet from inside my Update method:
globe.transform.Rotate((move.y*velocity*Time.deltaTime),0,(-move.x*velocity*Time.deltaTime),Space.World);
Your answer
Follow this Question
Related Questions
Camera in fixed position which rotates with player. 0 Answers
A node in a childnode? 1 Answer
change the rotation 1 Answer
Rotate script doesn't work! 1 Answer