Move mouse on the Y axis to move object on the Z axis.

Hi Folks.

I have an object floating in 3D space that hovers at a height of Y = 0. I have a script written that makes the object follow the mouse on the X axis side to side and that works great, but getting it to stay in alignment with the mouse point on the Z axis is proving problematic. Put simply, when the object is close to the camera, its close to the mouse, but as the mouse moves up the screen, the object moves away from the camera towards the horizon, and the mouse and object lose alignment with each other.

Does anyone have any ideas on how I can keep my object in alignment with the mouse pointer as the mouse moves upwards and the object moves off to the horizon?

Here is the code I’m currently using:

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

public class GridLocation : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
        //Position the GridLocation where the mouse points.
        Vector2 mouseCoords2D = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        Vector3 mouseCoords3D = new Vector3();
        mouseCoords3D = Camera.main.ScreenToWorldPoint(new Vector3(mouseCoords2D.x, 0, mouseCoords2D.y / 50));
        mouseCoords3D.y = 0.0f;
        this.transform.position = mouseCoords3D;
        Debug.Log(mouseCoords3D);
    }
}

Maybe use WorldToScreenPoint after setting the distance and only set the y axis leaving the other two the same.