4
\$\begingroup\$

I want the camera to follow the player and lag a little bit and then catch up with the player when the player halts. When stopped the player is in the center.

At the moment im at the point where i get the camera to move with the player but i dont know how to get the lag effect!

On the camera object

    void Update () {
    var newX =  player.transform.position.x;
    var newZ =  player.transform.position.z;
    var y = transform.position.y;
    transform.position = new Vector3(newX, y, newZ);    
}
\$\endgroup\$
2
  • \$\begingroup\$ Check out Lerp. It'll allow you to interpolate to the target position over time. \$\endgroup\$
    – House
    Commented Nov 19, 2013 at 22:36
  • 1
    \$\begingroup\$ You could also try attaching it with a spring \$\endgroup\$
    – floAr
    Commented Nov 19, 2013 at 22:37

2 Answers 2

2
\$\begingroup\$

In Unity LateUpdate is meant to be called after all the other updates are done. You'll want to utilize this method because you want to ensure the player position has been updated before you update the position of your camera. (Actually the Unity documentation mentions something very similar.)

Now that we know where to put it, there are two ways I can think of to make the camera follow the player:

Use any kind of interpolation: A simple example might be linear interpolation, expressed in parameterized vector notation, vectors are in bold

NewPos = CamPos + t * normalize(PlayerPos - CamPos);

Lerp is also a build in function that's available to you.

Using this with LateUpdate will give lag similar effect.

Elastic based camera: With the spring formula

F = k x

  • F stands for Force

  • k constant based on the spring stiffness (you can choose as you see fit)

  • x can be used distance between the camera and the player.

Note that Fcan be factored into F=m* a where m is mass(constant) and a is acceleration so you can modify the camera position using the calculated values.

In general this will give you a spring like behavior, but you need to multiply with some damping factor so it won't "bounce" forever.

\$\endgroup\$
0
0
\$\begingroup\$

One easy way is to just add a percentage of the desired position to the camera position each update.

void Update () {
  var newX =  player.transform.position.x;
  var newZ =  player.transform.position.z;
  var y = transform.position.y;

  var chaseSpeed = 0.05;

  transform.position = transform.position + 
       (new Vector3(newX, y, newZ) - transform.position) * chaseSpeed;    
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .