Smoothly following a moving object

I want the main camera to follow a spaceship. I attached the following code to the camera:

void Update ()
{
// target is the spaceship's transform
    Vector3 wantedPosition = target.TransformPoint (0, height, distance);
    transform.position = Vector3.Lerp (transform.position, 
wantedPosition, Time.deltaTime * damping);
    // ... code for rotation...
    }

However, as the target (my spaceship) moves forward, the camera shakes unpleasantly, I believe due to the Lerp function. Is there a way to avoid this and just have the camera move the same way as the spaceship does? Thanks.

You could use the 'built-in' script "Smooth Follow".

Attach the script (Component/Camera-Control/Smooth Follow) to your camera and adjust the values in the inspector.

For the 'shaking' problem, try moving the code you posted from Update() to FixedUpdate().

You could just use this script that I wrote - it’s not the fanciest of things but it gets the job done

I had the same problem with a spaceship shaking too

var playerMarker : Transform;

function LateUpdate () {
	transform.position = Vector3.Lerp(transform.position, playerMarker.position, Time.deltaTime * 100);
	transform.rotation = Quaternion.Lerp(transform.rotation, playerMarker.rotation, Time.deltaTime * 100);
}

// A simple smooth follow camera,
// that follows the targets forward direction

var target : Transform;
var smooth = 0.3;
var height = 0;
var distance = 5.0;
private var yVelocity = 0.0;

function Update () {
// Damp angle from current y-angle towards target y-angle
var yAngle : float = Mathf.SmoothDampAngle(transform.eulerAngles.y,
target.eulerAngles.y, yVelocity, smooth);
// Position at the target
var position : Vector3 = target.position;
// Then offset by distance behind the new angle
position += Quaternion.Euler(0+height, yAngle, 0) * Vector3 (0, 0, -distance);
// Apply the position
transform.position = position;

// Look at the target
transform.LookAt(target);

}

Why don’t you use Unity 5’s built in Smooth Follow script from the docs? It has no lagging issues for a powerful PC, but if you have issues, use FixedUpdate() instead of Update().

var target : Transform;
var smoothTime = 0.3;
private var velocity = Vector3.zero;

function Update () 
{
	// Define a target position above and behind the target transform
	var targetPosition : Vector3 = target.TransformPoint(Vector3(0, 5, -10));
		
	// Smoothly move the camera towards that target position
	transform.position = Vector3.SmoothDamp(transform.position, targetPosition, velocity, smoothTime);
}

It will not work if you have another script to control camera movement of ANY kind, so this is best used for a 2D game.