Getting Camera to Stop Following Player

Hi Everyone,

I am trying to make my camera follow the main character until he collides with a gameObject. So far everything works as expected, the camera follows the character, and I have a boolean that detects if the character collides with an object.

TL;DR The problem is that the camera moves it’s position back on it’s x axis, instead of just staying where it is.

Any ideas?

Here is my script:

 public float addPos;
 public Transform target;
 private Vector3 targetPos;

 void Update(){
     targetPos = new Vector3(target.position.x + addPos, transform.position.y, transform.position.z);
 }
 
 void LateUpdate () {
     if(gameObject.name == "Main Camera"){
         if(!Astronaut.isDead){
             transform.position = targetPos;
         }else{
             transform.position =   transform.position;
         }
     }

Thanks!

Try this:

public float addPos;
public Transform target;

void LateUpdate () {
  if(!Astronaut.isDead){
    transform.position = target.transform.position + (transform.position - target.transform.position).normalized * addPos;
  }
}