ScreenToWorldPoint works wrong after updating to 2019.3.5
Hello. I'm using ScreenToWorldPoint in editor with 2d camera for adding custom ways to manipulate objects on scene. It worked properly until update (I used 2019.3.0 before), now it gives wrong position — it match mouse position in top left corner, but is shifted more the more I move mouse to bottom right corner (see attached images).
The code I'm using for that:
var sceneCamera = SceneView.lastActiveSceneView.camera;
var sceneHeight = SceneView.lastActiveSceneView.camera.pixelHeight;
Vector2 MouseWorldPos = sceneCamera.ScreenToWorldPoint(new
Vector3(Event.current.mousePosition.x, sceneHeight - Event.current.mousePosition.y, 0));
Hope someone will help me figure out what changed, because before update this had worked as intended.
Answer by a436t4ataf · Mar 22, 2020 at 03:21 AM
UPDATE: ScreenToWorldPoint wasn't resolving correctly for me because I was calling it during the wrong phase of Event.type.
To answer your question, I believe you need to use:
var MouseScreenPosition = HandleUtility.GUIPointToScreenPixelCoordinate( e.mousePosition );
...this automatically adjusts for two UnityEditor "features" added in recent years: Retina support (which makes all coordinates in all existing code and all games ... wrong), and Unity's flip-the-Y bug, where they fail to take account of their own flipping in several of their APIs.
There is no "flip-the-Y bug" that I know. You may just confuse the different coordinate spaces. ScreenSpace has it's origin at the bottom left corner while GUI space has it's origin at the top left corner. Event.mousePosition is in GUI space while Input.mousePosition is in screen space.
They have multiple different semi-defined versions of what "screen" space is. Even the "Screen" API doesn't work reliably (it has some weird tricks that are only docuemnted in Forums where some of the Unity engineers have provided info - like the weird stuff it does inside OnInspectorGUI, but not always)
Right now, latest docs, official: https://docs.unity3d.com/ScriptReference/Input-mousePosition.html : "The bottom-left of the screen or window is at (0, 0)"
https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html: "Screenspace is defined in pixels. The bottom-left of the screen is (0,0)"
This stuff has been bugged in Unity since I started development back in 3.x days. It's well known, along with things like the screen position being misreported by 20 pixels on some OS's but not all because the Editor API's miscalculated the window size ... and only some of the Unity API's got fixed, so you had to memorise which ones worked and which ones needed correction.