Script for rotating a Unity game object 90 degrees

May 22, 2013 — Leave a comment

This Unity behavior script rotates the object it’s attached to by 90 degrees when the script’s rotate function is called. Just copy and paste the contents into a new JavaScript in Unity.

#pragma strict
 
public var seconds: float = .2;
 
private var rotating = false;
 
function rotateObject (thisTransform : Transform, degrees : Vector3) {
 
    if (rotating) return;
 
    rotating = true;
 
    var startRotation : Quaternion = thisTransform.rotation;
    var endRotation : Quaternion = thisTransform.rotation * Quaternion.Euler(degrees);
    var t : float = 0.0;
    var rate : float = 1.0/seconds;
 
    while (t < 1.0) {
    	t += Time.deltaTime * rate;
    	thisTransform.rotation = Quaternion.Slerp(startRotation, endRotation, t);
    	yield;
	}
 
	rotating = false;
 
}
 
function rotate() {
	rotateObject(transform, Vector3.forward*-90);
}

One way to call the rotate function from some other script is as follows:

 
var cube : GameObject = GameObject.Find("Cube");
cube.SendMessage("rotate");

Cheers!

ethan.york

Posts

Write for us!

We pay for great content that helps young and aspiring game makers along the path to mastery. You can earn extra income doing what you love and sharing what you learn! For more information, contact info@mastergamecraft.com.

No Comments

Be the first to start the conversation.

Leave a Reply