点击屏幕,关闭弹框

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AutoClosePanel : MonoBehaviour {
    public RectTransform rectTransform;
    public Camera uiCamera;
    
     Update is called once per frame
    void Update()
    {
#if UNITY_EDITOR
        if (Input.GetMouseButtonDown(0))
        {
            CheckClose(Input.mousePosition);
        }
#else
        if (Input.touchCount > 0) {
            for (int i = 0; i < Input.touchCount; i++)
            {
                CheckClose(Input.GetTouch(i).position);
            }
        }
#endif
    }

    void Close()
	{
        this.gameObject.SetActive(false);
	}

    void Show() {
        this.gameObject.SetActive(true);
    }

    void CheckClose(Vector3 clickPosition) {
        if (IsClickPanelOutsid(clickPosition))
        {
            Debug.Log("click out side");
            Close();
        }
        else {
            Debug.Log("click inside side");
        }
    }

    bool IsClickPanelOutsid(Vector3 clickPosition)
    {
       Vector3 clickWorldPos = uiCamera.ScreenToWorldPoint(clickPosition);
        Vector3[] cornerArray = new Vector3[4];// 左下,左上,右上,右下
        this.rectTransform.GetWorldCorners(cornerArray);
        Debug.Log("clickWorldPos:"+clickWorldPos);
        for (int i = 0; i < cornerArray.Length; i++)
        {
            Debug.Log("cornerArray:" + cornerArray[i]);
        }
            //Vector3 leftBottomPosition = uiCamera.WorldToScreenPoint(cornerArray[0]);
            //Vector3 rightTopPosition = uiCamera.WorldToScreenPoint(cornerArray[2]);
            //Debug.Log("leftBotomPoint:"+leftBottomPosition);
            //Debug.Log("rightTopPoint"+rightTopPosition);
            //Debug.Log("clickPosition:"+clickPosition);
        float minX = cornerArray[0].x;
        float minY = cornerArray[0].y;
        float maxX = cornerArray[2].x;
        float maxY = cornerArray[2].y;
        if (clickWorldPos.x > minX && clickWorldPos.y>minY && clickWorldPos.x < maxX && clickWorldPos.y < maxY)
        {
            return false;
        }
        return true;
    }




}

你可能感兴趣的:(unity-开发)