Clamping Camera to player using Raycast

Hello everyone,

I am quite new to Unity and currently trying to work with my top down camera clamping to a player in a 3d environment. My question would be how would I try to clamp my camera while using Raycast. I figured out on how to use the Raycast to move my camera around but have no idea how to convert into vectors in order to use the Mathf.Clamp function. Is there any guidance to this or alternative method that i am not aware of? Any direction or help would be appreciated.

Code that i am currently working on

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraTarget : MonoBehaviour
{

    [SerializeField] Camera cam;

    // Update is called once per frame
    void Update()
    {
        //this.transform.position = targetPos;
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out RaycastHit raycastHit))
        {
            transform.position = raycastHit.point;
        }
    }
}

The goal is to clamp the camera to the player position so that the camera can’t wander off a certain distance from the player itself.

Checking out the tutorial, this script has a similar function but for a 3D space:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TopDownTutorialCamera : MonoBehaviour
{
    public Camera cam;
    public Transform player;
    public float threshold;
    public float cameraHeight = 10f;

    void Update()
    {
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit))
        {
            Vector3 mousePos = hit.point;
            Vector3 targetPos = (player.position + mousePos) / 2f;

            targetPos.x = Mathf.Clamp(targetPos.x, -threshold + player.position.x, threshold + player.position.x);
            targetPos.y = cameraHeight;
            targetPos.z = Mathf.Clamp(targetPos.z, -threshold + player.position.z, threshold + player.position.z);

            transform.position = targetPos;
        }        
    }
}

I tested this script with a simple player cube and a world plane. The mousePos vector is not really neccessary but it keeps the tutorial code the same.


Tutorial: Basic Top Down Camera Look Movement! | #Unity Tutorial - YouTube