Simple DIY Camera using Lerp

Always kinda liked applying Lerp to the camera following … gives a more live feel to the entire movement. Did not use deltaTime as interpolation factor since that could lead to Ethan getting out of the camera view.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour {


    Transform _cameraArm;
    Transform _player;


	// Use this for initialization
	void Start () {
        GameObject maincamera = GameObject.FindGameObjectWithTag("MainCamera");
        _cameraArm = maincamera.transform.parent;
        _player = GameObject.FindGameObjectWithTag("Player").transform;
	}
	
	// Update is called once per frame
	void Update () {
		
	}

    void LateUpdate()
    {
        _cameraArm.transform.position = Vector3.Lerp(_cameraArm.transform.position, _player.transform.position, 0.1f);

    }
}
1 Like

Hi Reinhart,

I was able to accomplish the challenge but I am not sophisicated enough to use certain Vector3 functions such as Lerp. Can you please explain to me what this does to the code and how it makes the camera movement feel more real?

Thanks

Tim

Lerp is short for Linear Interpolation. It’s not just a vector3 function but can be used for all sorts of things (mathf.lerp, color.lerp,etc).

Essentially Lerp interpolate a point between two numbers by some percentage. So in his example above he is finding the point that is 10% (the. 1f) between the camera arm and player each frame and setting that to equal the camera arm. So each frame the camera essentially moves 10% if remaining distance.

This is Done to smooth movement, and tends to slow down movements towards the end, so there is not this sudden stop.

Example using simple numbers.(not vectors but the principal is the same) For ease we will also use an interpolate value of 50% (. 5)
If camera arm was say 10 and player was 2, 50% would be 6 the first frame, so camera arm would be 6. Next frame we interpolate between 6 and 2, 50% would be 4. Continuing this we would output 3, 1.5, etc.

As you can see, the camera arm starts moving fast then slows down as it reaches the end point. This creates a more natural motion for many things. Instead of a constant “movement this far each frame and stop at the end” its ends up being "Start moving at this speed and slow to a stop at the end).

I used lerp for my health bars in my version of Rocket Boost even,by applying it to an interface image.fillamount.

This is a quick reference, and I might have over simplified it. Check out the actual Unity docs for more info.

1 Like

Thanks James I just went through your post and it all makes perfect sense to me. Appreciate the help.

Tim

Ooops, was out for a week, thanks so much for your explanation James, that was an excellent answer.

Great info James!

That’s a pretty great idea, i usually just use the Vector3.SmoothDamp function to add a lively feel to the camera.

Privacy & Terms