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(), Input.mousePosition, Camera.main))
        //{
        //    Debug.Log("dds");
        //}
        //if (transform.GetComponent().rectTransform.rect.Contains(Input.mousePosition))
        //{
        //    Debug.Log("dd");
        //}  
        if(RectContainsScreenPoint(Input.mousePosition,can,transform.GetComponent(),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);
}

}

你可能感兴趣的:(unity判断点是否在某个rect内)