Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Camera.WorldToViewportPoint, but for planes

Discussion in 'Scripting' started by fires-, Nov 10, 2019.

  1. fires-

    fires-

    Joined:
    Oct 2, 2014
    Posts:
    4
    Hello,

    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?

    Thank you very much for your help!
     
  2. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
    I used this extension method to get the mouse position on the xz-plane.
    Code (csharp):
    1.  
    2. public static class ExtensionMethods_Camera
    3. {
    4.    private static Plane xzPlane = new Plane(Vector3.up, Vector3.zero);
    5.  
    6.    public static Vector3 MouseOnPlane(this Camera camera)
    7.    {// 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
    8.        Ray mouseray = camera.ScreenPointToRay(Input.mousePosition);
    9.        float hitdist = 0.0f;
    10.        if (xzPlane.Raycast(mouseray, out hitdist))
    11.        {// check for the intersection point between ray and plane
    12.            return mouseray.GetPoint(hitdist);
    13.        }
    14.        if( hitdist < -1.0f )
    15.        {// when point is "behind" plane (hitdist != zero, fe for far away orthographic camera) simply switch sign https://docs.unity3d.com/ScriptReference/Plane.Raycast.html
    16.            return mouseray.GetPoint( -hitdist );
    17.        }
    18.        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
    19.        return Vector3.zero;
    20.    }
    21. }
    22.