How to stop 3rd person camera going throught walls ?

Hello I am strugling with a 3rd person camera controll.

I want the camera to get closer to the player when it hits the wall or any obstacle.

But i don’t know how
I’ve tried putting colliders onto it but it doesn’t work.

Does anybody knows how to fix this ?

This is my code →

public float mouseSensitivity = 10;
public Transform target;
public float distanceFromTarget = 2;
public Vector2 MinMaxViewAngle = new Vector2( -40,85);

public float rotationSmoothTime = .12f;
Vector3 rotationSmoothVelocity;
Vector3 currentRotation;

float Xrotation;
float Yrotation;

// Update is called once per frame

private void Start()
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
void LateUpdate ()
    Xrotation += Input.GetAxis("Mouse X") * mouseSensitivity;
    Yrotation -= Input.GetAxis("Mouse Y") * mouseSensitivity;
    Yrotation = Mathf.Clamp(Yrotation, MinMaxViewAngle.x, MinMaxViewAngle.y);

    currentRotation = Vector3.SmoothDamp(currentRotation, new Vector3(Yrotation, Xrotation), ref rotationSmoothVelocity, rotationSmoothTime);
    transform.eulerAngles = currentRotation;

    transform.position = target.position - transform.forward * distanceFromTarget;
  1. remove the colliders.
  2. position/ move your lead game object… e.g. car or character.
  3. generate a vector backwards from your character, (maybe using combination of character’s facing, and up vectors) in the direction you want the camera to be, and also generate the point along that vector at the distance you want the camera to be from the object… say 10 unity units.
  4. Then use Physics.raycast( out hit) Which outputs collision data… if there is no collision… set your camera at that point… and set its transfor.forward to point at your character (the other direction along the vector)
  5. If there is a collision (or N collisions) it will give you a list of collision points in the ‘out’
    Choose the closest one, to position your camera there.