Scene |
public bool GetWorldToViewportMatrix( out Matrix4x4? worldToViewportMatrix, bool forceMatrixRefresh = false )
GetWorldToViewportMatrix gets Matrix4x4 that can be used to convert 3D coordinates to 2D viewport coordinates.
If the method returns true, than the worldToViewportMatrix was set; if false is returned than the matrix cannot be calculated (for example when MatrixCamera is used and the matrix cannot be inverted).
Important:
To calculate the screen coordinates of a 3D position you need multiply the position by the worldToViewportMatrix and then perform a perspective division (divide by W). See the following code:
bool adjustByDpiScale = true; Vector3 inputPosition3D = new Vector3(); Vector2 screenPosition = new Vector2(float.NaN, float.NaN); bool isWorldToViewportMatrixValid = _sceneView.GetWorldToViewportMatrix(out Matrix4x4 worldToViewportMatrix, forceMatrixRefresh: false); if (isWorldToViewportMatrixValid) { var screenPoint4 = Vector4.Transform(new Vector4(inputPosition3D.X, inputPosition3D.Y, inputPosition3D.Z, 1), worldToViewportMatrix); // Get screen position - perform perspective division (divide by W) if (screenPoint4.W != 0) { if (adjustByDpiScale) screenPosition = new Vector2(screenPoint4.X / (screenPoint4.W * _sceneView.DpiScaleX), screenPoint4.Y / (screenPoint4.W * _sceneView.DpiScaleY)); screenPosition = new Vector2(screenPoint4.X / screenPoint4.W, screenPoint4.Y / screenPoint4.W); } }