[RESOLVED] Camera.main.ScreenToWorldPoint always returns the position of the camera

Ok so I have a following script attached to my object:

private void OnMouseDown()
    {
        Vector3 mousePos;
        mousePos = Input.mousePosition;
        Debug.Log("C1: " + mousePos.ToString());
        mousePos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 0.0f));
        Debug.Log("C2: " + mousePos.ToString());
    }

When I click the object, the first debug returns sensible numbers, and seems to work. However, the second always returns the position of the main camera, and nothing else. Anyone knows what am I doing wrong? Thanks!

1 Like

That’s because your third parameter is 0. The third parameter means “distance from the camera”, so naturally if the distance from the camera is 0 it must be the position of the camera.

5 Likes

This gives the same result:

    private void OnMouseDown()
    {
        Vector3 mousePos;
        mousePos = Input.mousePosition;
        Debug.Log("C1: " + mousePos.ToString());
        mousePos = Camera.main.ScreenToWorldPoint(mousePos);
        Debug.Log("C2: " + mousePos.ToString());
        isHeld = true;
    }

This gives following output:
C1: (471.3, 330.0, 0.0)
C2: (1.0, 0.0, -8.0)

C1 changes when I click at different points of the object, but C2 is always the same.

Between line 5 and line 6, do this:

mousePos.z = 10;

that’s what Manta meant about the third coordinate. That means “tell me the world point at this distance into the screen,” in the example I suggest above, distance = 10; Your mileage may vary.

3 Likes

Oh, I see what you mean. I thought the method would simply translate the provided Vector3 into a world coordinate, not do some kind of a raycast. Thanks a lot both!

1 Like

Thank you for your answer! I never would have figured this out!

2 Likes