Need help with a Camera Soft Attach Script for Spaceship Game

Hey Guys,

I’m having trouble with my third person camera Soft Attach script for a Spaceship Combat game. Currently the script is always offsetting the camera in z direction and then rotating the camera at the same rate as the ship, rather than offsetting from the rear of the ship and tracking it.

I understand why this script isn’t working, but I can’t seem to figure out how to get the desired results (a camera that tracks behind the ship, with a smooth delay). Maybe I’m taking the wrong approach entirely?

private GameObject targetShip;
private List<Vector3> prevPositions = new List<Vector3>();
private List<Quaternion> prevRotations = new List<Quaternion>();
public float cameraLag = 100;
public Vector3 thirdPersonOffset = new Vector3(0.0f, 0.0f, 2.0f);

// Use this for initialization
void Start () 
{
    targetShip = transform.parent.gameObject;
}

void Update () 
{
    //Add the position and rotation of the ship to a list  
    prevPositions.Add(targetShip.transform.position);
    prevRotations.Add(targetShip.transform.rotation);

    //Once the list has exceeded a threshold, set the camera position to the last entry in the list
    if (prevPositions.Count > cameraLag)
    {
        transform.position = prevPositions[0] + thirdPersonOffset;
        prevPositions.RemoveAt(0);
        transform.rotation = prevRotations[0];
        prevRotations.RemoveAt(0);
    }

}

I know there are camera follow scripts available, but I’m writing this as a learning exercise.

Any help you can provide is much appreciated!

If you are looking for smoothing tracking, then Lerp() is a good choice. Here is a simple starter script. There are issues here still to be solved, but it demonstrates Vector3.Lerp().

#pragma strict
var trFollow : Transform; // Transform of game object to follow
var followDistance = 5.0;
var followHeight = 2.0;
var speed = 1.0;

function Update () {
	var desiredPosition = -trFollow.forward * followDistance + trFollow.position;
	desiredPosition.y = followHeight;
	transform.position = Vector3.Lerp(transform.position, desiredPosition, Time.deltaTime * speed);
	transform.LookAt(trFollow.position);
}