Unity 判断2D/3D坐标系下的一个点是否在指定的摄像机视野范围内

 1 using UnityEngine;
 2 
 3 public partial class CommonFunction
 4 {
 5     /// <summary>
 6     /// 视口坐标系是将Game视图的屏幕坐标系单位化,左下角(0,0),右上角(1,1)
 7     /// 摄像机视口坐标系下的坐标范围
 8     /// </summary>
 9     static Rect viewRect = new Rect(0, 0, 1, 1);
10 
11     /// <summary>
12     /// 以Game视图为准
13     /// 判断2D坐标系下的一个点是否在指定的摄像机视野范围内
14     /// 忽略z轴
15     /// </summary>
16     /// <param name="camera"></param>
17     /// <param name="uiWorldPos"></param>
18     /// <returns></returns>
19     public static bool Is2DPointInsideCameraView(Camera camera, Vector3 uiWorldPos)
20     {
21         if (null == camera)
22         {
23             return false;
24         }
25 
26         Vector3 viewPos = camera.WorldToViewportPoint(uiWorldPos);
27         return viewRect.Contains(viewPos);
28     }
29 
30     /// <summary>
31     /// 以Game视图为准
32     /// 判断3D坐标系下的一个点是否在指定的摄像机视野范围内
33     /// </summary>
34     /// <param name="camera"></param>
35     /// <param name="worldPos"></param>
36     /// <returns></returns>
37     public static bool Is3DPointInsideCameraView(Camera camera, Vector3 worldPos)
38     {
39         if (null == camera)
40         {
41             return false;
42         }
43 
44         //获取摄像机的六个平面
45         Plane[] planes = GeometryUtility.CalculateFrustumPlanes(camera);
46         for (int i = 0, iMax = planes.Length; i < iMax; ++i)
47         {
48             //判断一个点是否在平面的正方向
49             if (!planes[i].GetSide(worldPos))
50             {
51                 return false;
52             }
53         }
54 
55         return true;
56     }
57 }

 

posted @ 2021-06-24 22:15  小·糊涂仙  阅读(558)  评论(0编辑  收藏  举报