- Home /
Wrong world point mouse position
Hello,
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 :
Take the screen point's ray and get its intersection with your player's XZ plane for your non-collision target.
Answer by Bunny83 · Jun 28, 2019 at 06:53 PM
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.
Yeah, that was easy ... I've just checked some of my old scripts and I didn't made this mistake.
So thanks a lot for your help !
Your answer
Follow this Question
Related Questions
Camera.main.ScreenToWorldPoint works within Unity editor, but not in builds 0 Answers
Camera.ScreenToWorldPoint with Perspective camera 1 Answer
screenToWorld not working 1 Answer
Camera ScreenToWorldPoint Instatiating 1 Answer
Raycast object flies towards mouse on screen, i need it on floor 1 Answer