I try unsuccessfully to transform a plane into the viewport space (like Camera.WorldToViewportPoint, but just for a plane).
As a workaround, I transform three points to viewport space with which I can construct the plane (I use the Camera.WorldToViewportPoint function) and create the plane directly in viewport space. But then the normal is not stable and is sometimes positive and sometimes negative
Is there a method like “Camera.WorldToViewportPoint” also for planes?
I used this extension method to get the mouse position on the xz-plane.
public static class ExtensionMethods_Camera
{
private static Plane xzPlane = new Plane(Vector3.up, Vector3.zero);
public static Vector3 MouseOnPlane(this Camera camera)
{// calculates the intersection of a ray through the mouse pointer with a static x/z plane for example for movement etc, source: http://unifycommunity.com/wiki/index.php?title=Click_To_Move
Ray mouseray = camera.ScreenPointToRay(Input.mousePosition);
float hitdist = 0.0f;
if (xzPlane.Raycast(mouseray, out hitdist))
{// check for the intersection point between ray and plane
return mouseray.GetPoint(hitdist);
}
if( hitdist < -1.0f )
{// when point is "behind" plane (hitdist != zero, fe for far away orthographic camera) simply switch sign https://docs.unity3d.com/ScriptReference/Plane.Raycast.html
return mouseray.GetPoint( -hitdist );
}
Debug.Log ( "ExtensionMethods_Camera.MouseOnPlane: plane is behind camera or ray is parallel to plane! " + hitdist); // both are parallel or plane is behind camera so write a log and return zero vector
return Vector3.zero;
}
}