Wrong world point mouse position


I’m trying to use the method ScreenToWorldPoint(Vector3) to get my mouse position, but for some odd reasons it doesn’t work properly, it’s always equal to the Camera position.
I already made some scripts with this, but I never had this problem, so I’m confused.

Here is my code :

positionTargetted = CameraPlayer.GetComponent<Camera>).ScreenToWorldPoint(Input.mousePosition);
// set the y-axis to the player model y-axis
positionTargetted = new Vector3(positionTargetted.x, transform.position.y, positionTargetted.z);

I just want to use this to detect the mouse position when it’s out of bounds ( when raycasts can’t collide with any gameobject ), so the player will still be able to cast a spell towards this point.

Thanks a lot.

[EDIT] Here is the hierarchy :

alt text

That’s not wrong, that’s actually right. A screen position is a 2d position. A worldspace position is a 3d position. You’re missing one dimension. So a single screen point maps to infinite points along the line that starts at the camera origin. “ScreenToWorldPoint” actually takes a Vector3 not just a Vector2. The z coordinate specifies the desired distance from the camera in world units. Since you essentially pass 0 as z value you always get the camera origin since that’s where all lines meet.

You have to do

Vetor3 mousePoint = Input.mousePosition;
mousePoint.z = distanceFromCamera;
positionTargetted = CameraPlayer.GetComponent<Camera>().ScreenToWorldPoint(mousePoint);

distanceFromCamera need to be greater than 0.