Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

RectTransformUtility.RectangleContainsScreenPoint performance

Discussion in 'UGUI & TextMesh Pro' started by popMark, Jul 13, 2021.

  1. popMark

    popMark

    Joined:
    Apr 14, 2013
    Posts:
    114
    Hi,

    As odd as it sounds I'm having an issue with the performance of RectTransformUtility.RectangleContainsScreenPoint. I don't imagine its a crazy complex bit of functionality but from the CS reference I can only get as far as RectTransformUtility.PointInRectangle. Any chance of getting hold of the source code or an implementation I can maybe optimize for my needs?
     
  2. popMark

    popMark

    Joined:
    Apr 14, 2013
    Posts:
    114
    this is what Ive come up with but not sure if its a 100% match

    Code (CSharp):
    1. static bool RectangleContainsScreenPoint(RectTransform rt, Vector3 pos, Camera cam)
    2. {
    3.     var ray = cam.ScreenPointToRay(pos);
    4.     var plane = new Plane(rt.forward, rt.position);
    5.     if (plane.Raycast(ray, out var hit))
    6.     {
    7.         var hitPoint = ray.origin + ray.direction * hit;
    8.         var u = rt.InverseTransformPoint(hitPoint);
    9.         var rect = rt.rect;
    10.         return u.x > rect.xMin && u.x < rect.xMax &&
    11.                u.y > rect.yMin && u.y < rect.yMax;
    12.     }
    13.     return false;
    14. }
     
    Last edited: Jul 13, 2021
    Bero89 likes this.