代码之家  ›  专栏  ›  技术社区  ›  Olivier Pons

如何根据变换对象比较子对象?

  •  0
  • Olivier Pons  · 技术社区  · 7 年前

    我通过这个函数生成了很多对象:

    private GameObject CreateGhost(Transform p, float r, float g, float b)
    {
        GameObject result = Instantiate(
            gameObject, Vector3.zero, Quaternion.identity
        );
        Transform ghost_t = result.transform;
        RectTransform ghost_rt = result.GetComponent<RectTransform>();
        ghost_t.SetParent(p, false);
        ghost_rt.anchorMin = new Vector2(0f, 0f);
        ghost_rt.anchorMax = new Vector2(0f, 0f);
        ghost_rt.pivot = new Vector2(0f, 0f);
        ghost_rt.localScale = new Vector3(1f, 1f, 1f);
    
        Image m = result.GetComponent<Image>();
        m.color = new Color(r, g, b, 0.7f);
    
        return result;
    }
    

    知道参数 Transform p 总是一样的,在同一个“父”对象中有很多子对象。

    当用户单击一个对象时,我让它移动,我想看看它的矩形是否与另一个矩形重叠(注意:我不想使用 BoxCollider2D 目前)。

    我的循环如下:

    RectTransform ghost_rt = Ghost.GetComponent<RectTransform>();
    Rect ghost_r = new Rect(ghost_rt.anchoredPosition, 
        new Vector2(ghost_rt.rect.width, ghost_rt.rect.height));
    bool overlaps = false;
    foreach (Transform child_t in Dst.transform) {
        if (!GameObject.ReferenceEquals(child_t, ghost_rt)) {
            RectTransform rt = child_t.GetComponent<RectTransform>();
            Rect cmp_r = new Rect(rt.anchoredPosition,
                new Vector2(rt.rect.width, rt.rect.height));
            DebugText.text += "cmp_r:" + cmp_r + "\n";
            if (cmp_r.Overlaps(ghost_r)) {
                overlaps = true;
                break;
            }
        }
    }
    

    这种比较不起作用: (!GameObject.ReferenceEquals(child_t, ghost_rt)) .

    我也试过了,但没有成功: (!GameObject.ReferenceEquals(child_t.parent, ghost_rt.parent))

    如果我可以与另一个孩子(与当前对象不同)进行比较,那么要知道的方法是什么?

    1 回复  |  直到 7 年前
        1
  •  1
  •   joreldraw    7 年前

    您可以使用 Rect.Overlaps 要知道1个矩形是否与其他矩形重叠:

    子项重叠(ghost\r t.rect)