title: How to keep a pop up window on the screen. (Unity 2D, UI Image, Screen space overlay)
body: <p>How to keep a pop up window on the screen? (Unity 2D, UI Image, Screen space overlay)</p>
  <p>I have a pop up window 225x172 that I enable and change its transform to the mouse position as a pop up window.</p>
  <p>The problem I have is that if a user clicks near the screen edge, the pop up window isn't fully visible on the screen, as parts of its length and width will be out of the visible area.</p>
  <p>Solution is to check for the borders and adjust the pop up windows location to ensure for its length and width it appears as close to the mouse as possible but always fully visible.</p>
  <p>I wrote a function to return the adjusted Vector3, and it works ok until I adjust the screen resolution, and then it starts placing it in different non optimal positions.</p>
  <p>I guess I have to put some sort of scaling in? I imagine this is fairly common problem, but googling for a few hours hasn't given me any solutions...</p>
  <p>Anyone got a solution? Here is my method:</p>
  <pre><code>   private Vector3 KeepOnScreen(Vector3 MyInputPos, int width, int Height)   // returns vector3 always on screen
  {
      var corners = new Vector3[4];
      var RetRec = new Vector3();
      RetRec = MyInputPos;
  
      GetComponent&lt;RectTransform&gt;().GetWorldCorners(corners);
      // This returns the world space positions of the corners in the order
      // [0] bottom left, [1] top left [2] top right [3] bottom right
  
      int xmin = Mathf.RoundToInt(corners[0].x);
      int xmax = Mathf.RoundToInt(corners[2].x);
      int ymin = Mathf.RoundToInt(corners[2].y);
      int ymax = Mathf.RoundToInt(corners[3].y);
  
      //Debug.Log($&quot; MINS {xmin} {ymin}&quot;);
      //Debug.Log($&quot; MAXS {xmax} {ymax}&quot;);
      //Debug.Log($&quot; Mouse {MyInputPos.x} {MyInputPos.y}&quot;);
  
      RetRec.y = RetRec.y-20 - Height*2;  // move a bit to the right and down so the pop up window is not under mouse
      RetRec.x = RetRec.x + 40;
      if (MyInputPos.x + width*2 &gt; xmax) { RetRec.x = xmax - width * 2 - 40;} // adjust to keep whole window on screen
      if (MyInputPos.y -Height &lt; ymax) { RetRec.y = MyInputPos.y;}
  
      return RetRec;
  
  }
  </code></pre>