【问题标题】:how to check UI rect inside Canvas rect如何在 Canvas rect 中检查 UI rect
【发布时间】:2020-07-10 15:21:06
【问题描述】:

如何在 Canvas rect 中检查 UI rect?

rect.contains(Vector2) 是 Vector2...

rect.overlaps(Rect) 不会为假,除非完全在外面……

void Update()
{
    Vector2 pos;
    var screenPos = Camera.main.WorldToScreenPoint(targetTransform.position + offset);
    RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRectTransform, screenPos, uiCamera, out pos);
    if (!CheckInsideRect(myRectTransform.rect,canvasRectTransform.rect))
    {
        myRectTransform.localPosition = pos;
    }
}

我想要得到的结果

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您可以通过使用一些扩展方法来“手动”完成,例如

    public static class RectTransformExtensions
    {
        ///<summary>
        /// Returns a Rect in WorldSpace dimensions using <see cref="RectTransform.GetWorldCorners"/>
        ///</summary>
        public static Rect GetWorldRect(this RectTransform rectTransform)
        {
            // This returns the world space positions of the corners in the order
            // [0] bottom left,
            // [1] top left
            // [2] top right
            // [3] bottom right
            var corners = new Vector3[4];
            rectTransform.GetWorldCorners(corners);
    
            Vector2 min = corners[0];
            Vector2 max = corners[2];
            Vector2 size = max - min;
     
            return new Rect(min, size);
        }
     
        ///<summary>
        /// Checks if a <see cref="RectTransform"/> fully encloses another one
        ///</summary>
        public static bool FullyContains (this RectTransform rectTransform, RectTransform other)
        {       
            var rect = rectTransform.GetWorldRect();
            var otherRect = other.GetWorldRect();
    
            // Now that we have the world space rects simply check
            // if the other rect lies completely between min and max of this rect
            return rect.xMin <= otherRect.xMin 
                && rect.yMin <= otherRect.yMin 
                && rect.xMax >= otherRect.xMax 
                && rect.yMax >= otherRect.yMax;
        }
    }
    

    RectTransform.GetWorldCorners

    所以你会像这样使用它

    if (!canvasRectTransform.FullyContains(myRectTransform))
    {
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 2011-05-14
      • 2010-09-29
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多