Home > Enterprise >  how do I get mouse world position. X Y plane only in unity
how do I get mouse world position. X Y plane only in unity

Time:07-15

how do I get mouse world position. X Y plane only in unity . ScreenToWorldPosition isn't working. I think I need to cast a ray to mouse but not sure. This is what I am using. doesnt seem to give the correct coordinates or right plane. need for targeting and raycasting.

 private void Get3dMousePoint()
{
    var screenPosition = Input.mousePosition;
    screenPosition.z = 1;
    worldPosition = mainCamera.ScreenToWorldPoint(screenPosition);
    worldPosition.z = 0;
}

Just need XY coords.

CodePudding user response:

I tried with ScreenToWorldPoint () and it works. The key I think is in understanding the z coordinate of the position. Geometrically, in 3D space we need 3 coordinates to define a point. With only 2 coordinates we have a straight line with variable z parameter. To obtain a point from that line, we must choose at what distance (i.e. set z) we want the point sought to be. Obviously, since the camera is perspective, the coordinates you have at z = 1 are different from those at z = 100, differently from the 2D plane. If you can figure out how far away, that is, to set the z correctly, you can find the point you want. Just remember that the z must be greater than the minimum rendering distance of the chamber. I set that very value in the script. Also remember that the resulting vector will have the z equal to the z position of the camera the z value of the vector used in ScreenToWorldPoint.

void Get3dMousePoint()
{
    Vector3 worldPosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane));
    print(worldPosition);
}

if you think my answer helped you, you can mark it as accepted and vote positively. I would very much appreciate it :)

  • Related