- Home /
follow an object's x-axis and have it translate smoothly into another object's z-axis rotation
I'm making a 2.5 side scroll game. Game objects are 3D but the game is essentially 2D.
I have Ship B tracking Ship A's position along the x and y axis. When A moves past B in the side-scroll , I want B to Rotate around it's Y-axis as it is tracking A's movement.
I have script that does this but the Rotation around Z-axis is instantaneous. I need to slow it down to A's speed as it passes B from left to right. Sort of how an helicopter banks to make a turn. I don't need realism, Just need a smooth movement to show Ship B's 3D profile.
public class LookAtTarget : MonoBehaviour { public Transform target;
void Update()
{
float lockPos = 0;
{
transform.rotation = Quaternion.Euler(lockPos, transform.rotation.eulerAngles.y, lockPos);
}
if(target != null)
{
transform.LookAt(target);
}
}
}
Answer by Julian-Glenn · Aug 07, 2010 at 11:43 PM
Something like this may work *note not tested javaScript code
var rotationSpeed = 5.0; var theTarget : Transform;
function RotateTowards (position : Vector3) {
var direction = position - transform.position;
direction.y = 0;
if (direction.magnitude < 0.1)
return;
// Rotate towards the target
transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
transform.eulerAngles = Vector3(0, transform.eulerAngles.y, 0);
}
And call it like so:
RotateTowards(theTarget);
You'll have to change the Axis to suit your needs but this will rotate towards the target at whatever speed you wish
Thanks for the code but I'm getting an error msg.
The best overload for the method 'LookAtZturn.RotateTowards(UnityEngine.Vector3)' is not compatible with the argument list '(UnityEngine.Transform)'.
You should be calling: RotateTowards(theTarget.position); It's expecting a Vector3, but being passed a Transform.