RaycastHit and Camera through walls

Hello!

I’ve been trying to make my camera not move through walls with RaycastHit, but I really can’t get it to work. This is what I’ve come up with so far.

void Update ()
		{
				RaycastHit wallHit = new RaycastHit ();
				Ray wallRay = new Ray (car.transform.position, camera.transform.position);
		
				if (Physics.Raycast (wallRay, out wallHit, distance)) {
						if (wallHit.collider.tag == "Wall") {
								camera.transform.position = wallHit.point;
						}
				} 
		}

Can you spot what I am doing wrong? Any help is massively appreciated!

The direction of your ray is way off.

Think of it this way: Your car is at (50, 10000, 20), so your camera is at, say, (50, 10005, 25). Your ray is shooting from (50, 10000, 20) and going to (100, 20005, 45).

Your ray needs to be:

Ray wallRay = new Ray (car.transform.position, camera.transform.position - car.transform.position);