Slowly Change One Object's Rotation To Match Another's

Hello, im fairly new to Javascripting and im having a hard figuring out how to slowly change the rotation of one object to match the rotation of another object. This is my script so far:


var garage : Transform;
var garageTargetA : Transform;
var garageTargetB : Transform;
var speed = 10;

function OnMouseOver () {
Debug.Log("You're Mouse Hovered");
   if (Input.GetKeyDown("e") && garage.position.y == garageTargetB.position.y) {
      garage.position = garageTargetA.position * Time.deltaTime * speed;
      garage.rotation = garageTargetA.rotation * Time.deltaTime * speed;
      Debug.Log("The Garage Has Opened");
   }
   if (Input.GetKeyDown("e") && garage.position == garageTargetA.position) {
      garage.position = garageTargetB.position * Time.deltaTime * speed;
      garage.rotation = garageTargetB.rotation * Time.deltaTime * speed);
      Debug.Log("The Garage Has Closed");
   }
}

Please Help and Thank you!

2 Answers

2

i think you search for this: Unity - Scripting API: Quaternion.RotateTowards

Thank you, but for some reason the Object just teleported to a random location.

There is probably some nifty Unity Transform method to do this that I’m not thinking of, but I was always fond of Lerp and Slerp anyway. The following example does what I think you want, allowing you to specify the target and the merge time it takes to merge with the position/rotation of the target object.

#pragma strict

var target : Transform;
var mergeTime : float = 5;

function Start () {

	yield Merge(target, mergeTime);
}

function Merge(to : Transform, seconds : float)
{
	var timer : float = seconds;
	var fromPosition : Vector3 = transform.position;
	var fromRotation : Quaternion = transform.rotation;
	
	while(timer > 0)
	{
		transform.position = Vector3.Lerp(fromPosition, to.position, (seconds - timer)/seconds);
		transform.rotation = Quaternion.Slerp(fromRotation, to.rotation, (seconds - timer)/seconds);
		timer -= Time.deltaTime;
		yield;
	}
}