how to rotate an object to a point over a certain period of time?
function RotateInXSeconds( float xSeconds, Vector3 angles )
{
var counter : float = 0.0;
var startRot : Quaternion = transform.rotation;
var endRot: Quaternion = transform.rotation * Quaternion.Euler(angles);
while( counter < xSeconds )
{
transform.rotation = Quaternion.Lerp( startRot, endRot, counter / xSeconds );
yield null;
counter += Time.deltaTime;
}
print( "Done" );
}
Doc :
http://unity3d.com/support/documentation/ScriptReference/Quaternion.Lerp.html
http://unity3d.com/support/documentation/ScriptReference/Quaternion-operator_multiply.html
http://unity3d.com/support/documentation/ScriptReference/Coroutine.html
You can try the Animation Clip to do that. By specifying a key frame on the certain position of timeline, you can rotate your game object and then play this clip to watching result. Your game object will rotate to the certain angles over the time along the timeline axis. Here is the ref:
http://unity3d.com/support/documentation/Manual/Animation.html
There are several ways. The easiest way is to define the direction and let the object rotate gradually in Update:
var target: Transform; var speed: float = 5; function Update(){ // find the target direction: var dir: Vector3 = target.position - transform.position; // calculate the necessary rotation: var rot: Quaternion = Quaternion.LookRotation(dir); // rotate gradually to it: transform.rotation = Quaternion.Slerp(transform.rotation, rot, speed * Time.deltaTime); }
This will make the object rotate gradually to point its local forward direction to the target - but the rotation is fast at first, and slows down when reaching the desired rotation. If you want to rotate in a fixed time, it’s better to use a coroutine like this:
var duration: float = 1.5; // rotate in 1.5s private var rotating = false; function RotateTo(target: Vector3){ rotating = true; var dir: Vector3 = target.position - transform.position; var endRot: Quaternion = Quaternion.LookRotation(dir); var iniRot: Quaternion = transform.rotation; var t: float = 0; while (t < 1){ t += Time.deltaTime/duration; transform.rotation = Quaternion.Slerp(iniRot, endRot, t); yield; } rotating = false; }
You can call RotateTo(targetPoint) to start the rotation - the coroutine will run in the background during the duration time and stop exactly when pointing to targetPoint. But you should not call RotateTo again while it’s already rotating - that’s why the variable rotating was created:
if (!rotating) RotateTo(player.position);