unity里面判断两个image是否重叠

由于UGUI里面的对象做触发检测很麻烦而且不方便,偶尔还会不准确,因此可以使用更精准有效的方式,通过检测两个Image是否发生重叠。

矩形相交的判断,代码如下:

using UnityEngine;

public class ImageOverlap : MonoBehaviour
{
    private RectTransform rt;
    public RectTransform TargetRt;
    
    void Start()
    {
        rt = GetComponent<RectTransform>();

        //JudgeOverlap();
    }
    public void JudgeOverlap()
    {
        Debug.Log("当前是否重叠:" + RectTransToScreenPos(rt, null).Overlaps(RectTransToScreenPos(TargetRt, null)));

    }
    /// 
    /// 相机传入主要取决于rt都画布,如果画布使用camera模式,则传入对应的相机,反之为null,注意:wordspace模式我没有测试,不在此次记录范围
    /// 
    /// 
    /// 
    /// 
    public static Rect RectTransToScreenPos(RectTransform rt, Camera cam)
    {
        Vector3[] corners = new Vector3[4];
        rt.GetWorldCorners(corners);
        Vector2 v0 = RectTransformUtility.WorldToScreenPoint(cam, corners[0]);
        Vector2 v1 = RectTransformUtility.WorldToScreenPoint(cam, corners[2]);
        Rect rect = new Rect(v0, v1 - v0);
        return rect;
    }
}

注意:上图的画布使用Overlay模式,所以Camera参数直接传入null!!!

该功能可以结合拖拽image的脚本使用,脚本如下:

using UnityEngine;
using UnityEngine.EventSystems;
public class ImageDrap : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    private RectTransform rectTransform;
   
    void Start()
    {
        rectTransform = GetComponent<RectTransform>();
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("开始拖拽");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 pos;
        RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, eventData.position, eventData.enterEventCamera, out pos);
        rectTransform.position = pos;
    }
    public void OnEndDrag(PointerEventData eventData)
    {
        Debug.Log("结束拖拽");
        GetComponent<ImageOverlap>().JudgeOverlap();
    }
}

测试结果如果:

unity里面判断两个image是否重叠_第1张图片
unity里面判断两个image是否重叠_第2张图片

有疑问欢迎vx咨询159-7084-3394

你可能感兴趣的:(unity游戏开发,关于VR方向,unity,游戏引擎,ui)