Ray from camera that has an angle and calculating right position

I’m trying to do a character controller like shooty skies game and I’m sending a ray from a camera and camera has some angle and equating the hit point to the transform of an object, but if the Y of the object is not 0, of course, it looks like it’s not folowingthe Mouse position (Ray hit point ), because of the angle of the camera. How can I calculate this and make it look right?

my code:

void Update()

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

        if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
            transform.position = new Vector3(hit.transform.position.x, transform.position.y, hit.transform.position.z) ;

and this is an example image

How this thing is lookingt


Mouse have a position, but is a position ont he screen ( not on the world.

So first, you ened to get the mouse position

And then change that position from screen to world coordinates

Then cast a ray from the camera, direct to mouse world position, so it will hit “under the mouse”

You just need this magic functons :smiley:

Good luck!