# Follow camera in 2d game

Recently I am working on racing game. For that I am following camera with car. But using following code it creates jerk in movement.

I don’t want any rotation, I just want to follow in y direction.

``````public class SmoothCameraFollow : MonoBehaviour
{
private Vector3 cameraOffset, playerOffset;
public float speed;
public Transform target;
void Start ()
{
cameraOffset = transform.position;
playerOffset = target.position;
}

void LateUpdate ()
{
Vector3 targetPosition = target.position + cameraOffset - playerOffset;
targetPosition.x = 0;
transform.position = targetPosition;
}
}
}
``````

Please give some help in this.

Instead of exactly matching the camera’s movement to the car’s movement, you need to add some `softening` or interpolation of the difference between where the camera is at, and where it needs to get to.

You could do it by a) finding the car position, b) calculating where you want the camera to be (as you have it now), c) not actually setting the camera to this position, d) instead finding the DIFFERENCE between the camera’s current position and the predicted new position, e) SCALING that difference down, e.g. multiply it by 0.01 or something, f) add that scaled-down difference to the original camera’s position. The more you scale the difference the slower the camera’s reaction will be. It will look pretty smooth though, gradually catching up to the changes in the car’s movement. For quicker reactiveness, multiply the difference in positions by a bigger number e.g. 0.1.

1 Like

What @imaginaryhuman_1 said can be done with Mathf.Lerp or Vector3.Lerp with a very strong coefficient.

Try using this. It creates a nice smooth spring camera.

1 Like

At present, I am getting good result with following code only compare to any other code.

``````public class SmoothCameraFollow : MonoBehaviour
{

private Vector3 cameraOffset, playerOffset;
private Vector3 refVelocity = Vector3.zero;
public Transform target;

void Start ()
{
cameraOffset = transform.position;
playerOffset = target.position;
}

void LateUpdate ()
{