- Home /
script: turn object gradually to a desired rotation
when my object jumps and is airborne I want it to rotate so that x-rotation, y-rotation and z-rotation are 0. However it has to rotate to that point gradually. How do make a script that can accomplish this?
Thank you for your help.
Comment
Answer by whydoidoit · Jan 04, 2013 at 01:47 PM
Something like:
scalingFactor = 1; // Bigger for slower
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.identity, Time.deltaTime/scalingFactor);
This just did the trick:
var scalingFactor = 1;
var rotateTo : Transform;
var rotateFrom : Transform;
if(grounded == false) {
transform.rotation = Quaternion.Slerp(rotateFrom.rotation, rotateTo.rotation, Time.deltaTime/scalingFactor);
}
Answer by MarkFinn · Jan 04, 2013 at 02:07 PM
using UnityEngine;
using System.Collections;
public class Resetter : MonoBehaviour {
System.Random rnd;
bool running=false;
// Use this for initialization
void Start () {
rnd=new System.Random((int)(Time.time*100));
}
// Update is called once per frame
void Update () {
}
void OnGUI()
{
if (!running){
if (GUI.Button (new Rect(10, 10, 100, 100), "Then Hit me")){
StartCoroutine(ZeroMeOut(5));
}
if (GUI.Button (new Rect(200, 200, 100, 100), "Hit me First")){
transform.Rotate(new Vector3(rnd.Next(90), rnd.Next(90), rnd.Next(90)));
}
}
GUI.Label (new Rect(200, 10, 100, 100), "("+((int)transform.rotation.eulerAngles.x)+", "+((int)transform.rotation.eulerAngles.y)+", "+((int)transform.rotation.eulerAngles.z)+" )");
}
private IEnumerator ZeroMeOut(float timeInSeconds)
{
running=true;
Vector3 startRot = transform.rotation.eulerAngles;
float startTime=Time.time;
do{
float lerpValue = (Time.time-startTime)/timeInSeconds;
transform.rotation=Quaternion.Euler(
new Vector3(
Mathf.Lerp(startRot.x, 0, lerpValue),
Mathf.Lerp(startRot.y, 0, lerpValue),
Mathf.Lerp(startRot.z, 0, lerpValue)));
yield return 0;
}
while (Time.time<startTime+timeInSeconds);
//transform.rotation=Quaternion.Euler(Vector3.zero);
running=false;
}
}
See $$anonymous$$ike's rather more elegant solution above for a sane way to do this.