Camera Colliding with Terrain

Hello, I want to make my camera in my racing game collide with the terrain so it cant go through the terrain at all. This is the code I added to my script in order to try and achieve the behaviour I’m looking for:

using UnityEngine;
using System.Collections;

public class SmoothFollow : MonoBehaviour 
{
    private Ray ray;
    private RaycastHit hit;
    public GameObject player;
    public Transform target;

    void Start()
    {
        ray = new Ray(target.position, target.position - transform.position);
    }

    void Update()
    {
        if (Physics.Raycast(ray, out hit))
        {
             transform.position = ray.GetPoint(hit.distance - 1);
        }

        if(cameraNum == -1)
	    {
		     cameraDistance = Vector3.Distance(target.position, target.position) + 140;
	    }
	    // Gets the sled position and adds the camera height to it.
	    newHeight.y = target.transform.position.y + cameraHeight;
	
	    if(Input.GetKeyUp(KeyCode.C) && allowCameraChange)
	    {
		    ChangeCameraView();		
	    } 
    }
}

Its not giving me any errors its just not doing anything at all besides the normal camera stuff I have going on in the script. Any help or insight would be awesome.

Thanks,
Hans

Your ray does not change, so nothing is going to happen. You need to be doing the raycast every frame, or at some regular interval for occlusion/collision testing to work.