Home c# ScreenWorldPoint Returns Camera Coordinates when parameter input.mouseposition

ScreenWorldPoint Returns Camera Coordinates when parameter input.mouseposition

Author

Date

Category

Learning Unity and can not figure out the screenoworldpoint:

if (input.getmousebutttonnt (0))
{
  Debug.log (GetComponent & LT; Camera & GT; (). ScreenWorldPoint (input.mouseposition));
}

It seems that everything is written correctly and the coordinates should translate, but where do not press – it gives the coordinates of the camera itself. Help me figure out.


Answer 1, Authority 100%

We go to documentation :

Specifically, we are interested in the addict to the first overload of the method:

Plus a z Position for depth (for example, a Camera Clipping Plane)


Camera is, generally speaking, a rather confusing thing for an unprepared person:

often , the screen is Near Clipping Plane , in any case, “screen” is a securing froustum camera plane where the mouse and clicks in this case.

The problem is that the points on this plane have 3 coordinates:

  1. X – X axis
  2. y – axis y
  3. z – distance from the camera to the plane

And the mouse, purely logically, has 2 coordinates – x and y, about some Z it does not know anything. input.mouseposition generally returns vector3 , with 0 instead of coordinate z. And in fact, this is a valid situation: a plane at a distance of 0 from the chamber is a plane with a “zero” area, i.e. Any point on this plane will be distrounded into 3D space with such coordinates:

  • x = & gt; Camerax + 0 0, because we have a “empty” plane, nowhere there
    Frame
  • y = & gt; Camerey + 0 0, because See x
  • z = & gt; Cameraz + 0 0,
    Because We passed the zero distance from the plane to the camera

As a result, we get a conversion:

input: vector3 (x, y, 0)
Output: Vector3 (Camerax, Cameray, Cameraz)

As can be seen, the coordinates of the original point at all do not affect the transformed coordinates, and everything lies in Z = 0 in the input data.

Solution?

Use a screen plane that is removed from the camera for a distance prescribed in the chamber:

var screenocameradistance = camera.Nearclipplane;

tl; dr

var camera = getcomponent & lt; camra & gt; ();
var mousepos2d = input.mouseposition;
var screenocameradistance = camera.Nearclipplane;
var mouseposnearclipplane = new vector3 (mousepos2d.x, mousepos2d.y, screenocameradistance)
// desired point in global coordinates
var WorldPointPos = Camera.ScreentWorldPoint (MousePosNearclipplane);

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions