Camera following spaceship problem

I’m having a small problem with a script designed to make a camera “float” behind my spaceship (a :)). It’s actually working pretty well except for the fact that when the cube’s forward axis is oriented straight up or straight down the camera completely flips over on its z-axis! Here is an example of my code:

var target : Transform;
var distanceToFollow : float = 5.0;
var moveSpeed : float = 1.0;
var rotationSpeed : float = 1.0;

private var targetRay : Ray;


function Update () {

	//move the camera into position behind the target
	targetRay = new Ray(target.position,-target.forward);
	point = targetRay.GetPoint(distanceToFollow);
	point = Vector3.Slerp(transform.position, point, Time.deltaTime * moveSpeed);
	transform.position = point;
	
	//rotate the camera to match the rotation of the target	
	transform.LookAt(target);
	
	targetZRotation = target.rotation.eulerAngles.z;
	currentZRotation = transform.eulerAngles.z;
	currentZRotation = Mathf.LerpAngle(targetZRotation, currentZRotation, Time.deltaTime * rotationSpeed);
	makeRotation = Quaternion.Euler(0,0,currentZRotation).eulerAngles;
	transform.Rotate(makeRotation);
	

}

Has anyone had this problem before??

Shot in the blue: You might be running into a gimbal lock problem because you’re using Euler angles.

hmmm I see. Is there a way to get around this or an even better question what should I use in the place of Euler angles??

hmmm I see. Is there a way to get around this or an even better question what should I use in the place of Euler angles??

-EDIT-
Wait! I found that my LookAt call was using the world’s up vector, not the targets!

For anyone else that has this problem this is my new code:

var target : Transform;
var distanceToFollow : float = 5.0;
var height : float = 1.0;
var moveSpeed : float = 1.0;
var rotationSpeed : float = 1.0;

private var targetRay : Ray;


function Update () {

	//move the camera into position behind the target
	targetRay = new Ray(target.position,-target.forward);
	point = targetRay.GetPoint(distanceToFollow);
	point = Vector3.Slerp(transform.position, point, Time.deltaTime * moveSpeed);
	transform.position = point;
	
	//rotate the camera to match the rotation of the target	
	transform.LookAt(target,target.up);
	
	//correct the z orientation of the camera to match the target's
/*	targetZRotation = target.rotation.eulerAngles.z;
	currentZRotation = transform.eulerAngles.z;
	currentZRotation = Mathf.LerpAngle(targetZRotation, currentZRotation, Time.deltaTime * rotationSpeed);
	makeRotation = Quaternion.Euler(0,0,currentZRotation).eulerAngles;
	transform.Rotate(makeRotation);*/
	

}

I commented out the whole z correction because LookAt has it built in!!
Thanks for your reply.

I know exactly the problem you’re having. Using iTween for movement doesn’t help, either.

You wouldn’t happen to have any experience with collision detection, would you?