• Unity 判断两个UI是否相交


    今天碰到要判断两个UI是否相交的交互。

    尝试了下,发现有两个方法都成功了。

    1、使用Collider2D组件

    分别创建两个Image组件,并且添加Collider2D组件,其中一个还要添加Rigidbody2D组件,如下图:

    然后创建个判断脚本“UIintersect.cs",具体脚本代码如下,把脚本拉到场景中,当物体碰到一起是就能检测到它们是否相交了。

    1. public Image image1;
    2. public Image image2;
    3. private Collider2D collider1;
    4. private Collider2D collider2;
    5. // Start is called before the first frame update
    6. void Start()
    7. {
    8. // 获取image1和image2的Collider组件
    9. collider1 = image1.GetComponent<Collider2D>();
    10. collider2 = image2.GetComponent<Collider2D>();
    11. }
    12. // Update is called once per frame
    13. void Update()
    14. {
    15. // 检测两个Collider是否相交
    16. if (collider1.IsTouching(collider2))
    17. {
    18. Debug.Log("UI相交了!");
    19. }
    20. else
    21. {
    22. Debug.Log("UI没有相交!");
    23. }
    24. }

    2、使用RectTransform组件和边界框

    本方法只需要脚本获取UI的RectTransform,然后判断它们的边界是否相交即可。

    代码如下:

    1. public RectTransform uiElement1;
    2. public RectTransform uiElement2;
    3. // Start is called before the first frame update
    4. void Start()
    5. {
    6. }
    7. // Update is called once per frame
    8. void Update()
    9. {
    10. if (CheckCollision(uiElement1, uiElement2))
    11. {
    12. Debug.Log("UI相交了!");
    13. }
    14. else
    15. {
    16. Debug.Log("UI没有相交!");
    17. }
    18. }
    19. private bool CheckCollision(RectTransform rectTransform1, RectTransform rectTransform2)
    20. {
    21. Rect rect1 = rectTransform1.rect;
    22. Rect rect2 = rectTransform2.rect;
    23. Rect worldRect1 = GetWorldRect(rectTransform1);
    24. Rect worldRect2 = GetWorldRect(rectTransform2);
    25. return worldRect1.Overlaps(worldRect2);
    26. }
    27. private Rect GetWorldRect(RectTransform rectTransform)
    28. {
    29. Vector3[] corners = new Vector3[4];
    30. rectTransform.GetWorldCorners(corners);
    31. Vector3 bottomLeft = corners[0];
    32. Vector3 topRight = corners[2];
    33. return new Rect(bottomLeft.x, bottomLeft.y, topRight.x - bottomLeft.x, topRight.y - bottomLeft.y);
    34. }

    把代码拉到场景中,也能判断UI是否相交。

    总的感觉两种方法都不错。

    效果:Unity判断两个UI是否相交_哔哩哔哩_bilibili

  • 相关阅读:
    二、MongoDB简介及基本操作
    [PowerQuery] PowerAutoMate 刷新PowerBI 数据
    5G专网技术研究及其行业应用
    Terraform 华为云最佳实践
    java计算机毕业设计后勤管理系统源码+mysql数据库+系统+lw文档+部署
    类和对象(前)
    快速抽取resnet_v2_152中间的特征层
    vue使用websocket与springboot通信
    flutter web 中嵌入一个html
    arm64 虚拟地址物理地址转换
  • 原文地址:https://blog.csdn.net/mr_five55/article/details/134277624