0
\$\begingroup\$

I am building a topdown 3d shooter. I want to find the position of the mouse in the world so I can shoot a bullet from the player's position towards the mouse position on mouse click. So to begin with I'm trying to get the positions of both objects:

void Update()
        {
                if (Input.GetMouseButtonDown(0))
Debug.Log(
      "Player position = " + transform.position + 
    "; Mouse position = " + Input.mousePosition + 
    "; Mouse position in world = " + mainCamera.ScreenToWorldPoint(Input.mousePosition));
        }

These are the results:

Clicking right on top of the player Player position = (0.0, 0.5, 0.0);
Mouse position = (968.3, 543.1, 0.0);
Mouse position in world = (0.0, 25.0, 0.0)

Above the player Player position = (0.0, 0.5, 0.0);
Mouse position = (957.9, 686.7, 0.0);
Mouse position in world = (0.0, 25.0, 0.0)

Right of the player Player position = (0.0, 0.5, 0.0);
Mouse position = (1114.0, 557.7, 0.0);
Mouse position in world = (0.0, 25.0, 0.0)

Below the player Player position = (0.0, 0.5, 0.0);
Mouse position = (962.1, 414.1, 0.0);
Mouse position in world = (0.0, 25.0, 0.0)

Left of the player Player position = (0.0, 0.5, 0.0);
Mouse position = (822.7, 557.7, 0.0);
Mouse position in world = (0.0, 25.0, 0.0)

So looks like the translation to world coordinates always yields the same result?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You're passing a value of zero in the z coordinate, which means "give me a point zero units from the camera". There's only one such position: the camera's position itself. If you want to get positions in a deeper depth plane, you need to provide a non-zero z depth value. You could also use ScreenPointToRay and then raycast along that ray to find the closest collider surface under the mouse position. \$\endgroup\$
    – DMGregory
    Oct 2 at 13:57

Browse other questions tagged or ask your own question.