unity判断点是否在某个rect内

using UnityEngine;
using UnityEngine.UI;

public class mytest : MonoBehaviour
{
public Canvas can;
void Update()
{
//if (Input.GetMouseButtonUp(0))
//{
// print(Mathf.Abs(Vector2.Distance(Input.mousePosition, Camera.main.WorldToScreenPoint(transform.position))));
// if(Mathf.Abs(Vector2.Distance(Input.mousePosition, Camera.main.WorldToScreenPoint(transform.position)))<68)
// {
// transform.localScale += Vector3.one;
// }

    //}

    if (Input.GetMouseButtonUp(0))
    {
        //if(RectTransformUtility.RectangleContainsScreenPoint(transform.GetComponent<RectTransform>(), Input.mousePosition, Camera.main))
        //{
        //    Debug.Log("dds");
        //}
        //if (transform.GetComponent<RawImage>().rectTransform.rect.Contains(Input.mousePosition))
        //{
        //    Debug.Log("dd");
        //}  
        if(RectContainsScreenPoint(Input.mousePosition,can,transform.GetComponent<RectTransform>(),Camera.main))
        {
            Debug.Log("点击了");
        }
    }            
}

public Rect GetSpaceRect(Canvas canvas, RectTransform rect, Camera camera)
{
    Rect spaceRect = rect.rect;
    Vector3 spacePos = GetSpacePos(rect, canvas, camera);
    //lossyScale
    spaceRect.x = spaceRect.x * rect.lossyScale.x + spacePos.x;
    spaceRect.y = spaceRect.y * rect.lossyScale.y + spacePos.y;
    spaceRect.width = spaceRect.width * rect.lossyScale.x;
    spaceRect.height = spaceRect.height * rect.lossyScale.y;
    return spaceRect;
}
private Vector3 GetSpacePos(RectTransform rect, Canvas canvas, Camera camera)
{
    if (canvas.renderMode == RenderMode.ScreenSpaceOverlay)
    {
        return rect.position;
    }
    return camera.WorldToScreenPoint(rect.position);

}
private void GetSpaceCorners(RectTransform rect, Canvas canvas, Vector3[] corners, Camera camera)
{
    if (camera == null)
    {
        camera = Camera.main;
    }
    rect.GetWorldCorners(corners);
    if (canvas.renderMode == RenderMode.ScreenSpaceOverlay)
    {

    }
    else
    {
        for (var i = 0; i < corners.Length; i++)
        {
            corners[i] = camera.WorldToScreenPoint(corners[i]);
        }
    }
}

public bool RectContainsScreenPoint(Vector3 point, Canvas canvas, RectTransform rect, Camera camera)
{
    if (canvas.renderMode != RenderMode.ScreenSpaceOverlay)
    {
        return RectTransformUtility.RectangleContainsScreenPoint(rect, point, camera);
    }

    return GetSpaceRect(canvas, rect, camera).Contains(point);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值