GeometryUtility 工具类 常用方法

发布时间:2026/7/10 5:42:55
GeometryUtility 工具类 常用方法 1.CalculateBounds作用计算一组顶点变换后对应的最小轴对齐包围盒AABB是非常常用的辅助方法。方法说明publicstaticBoundsCalculateBounds(Vector3[]positions,Matrix4x4transform);positions输入的顶点数组一般是模型本地空间的顶点transform顶点的变换矩阵比如把本地顶点转世界空间就传入物体的transform.localToWorldMatrix不需要变换传Matrix4x4.identity即可示例// 计算模型在世界空间的包围盒MeshmeshGetComponentMeshFilter().sharedMesh;Matrix4x4localToWorldtransform.localToWorldMatrix;BoundsworldBoundsGeometryUtility.CalculateBounds(mesh.vertices,localToWorld);2.IntersectRayAABB作用快速测试射线和轴对齐包围盒AABB是否相交常用于批量检测的快速剔除。方法说明publicstaticboolIntersectRayAABB(Rayray,Boundsbounds,outfloatdistance);返回值true表示射线和包围盒相交false表示不相交distanceout参数返回射线起点到交点的距离示例// 鼠标点击选物体先通过包围盒快速剔除不相交的物体RayrayCamera.main.ScreenPointToRay(Input.mousePosition);foreach(varrendinallRenderers){// 先测包围盒相交仅对相交的物体做后续高精度碰撞检测节省性能if(GeometryUtility.IntersectRayAABB(ray,rend.bounds,outfloatdist)){HandleClick(rend.gameObject);}}3.BoundsToPoints作用把AABB包围盒转换为它8个角顶点的数组常用于包围盒可视化、自定义几何检测。方法说明publicstaticvoidBoundsToPoints(Boundsbounds,Vector3[]points);要求传入的points数组长度必须为8方法会把8个顶点按顺序填充到数组中示例// 用Gizmos在Scene窗口绘制物体包围盒Vector3[]cornersnewVector3[8];GeometryUtility.BoundsToPoints(rend.bounds,corners);for(inti0;icorners.Length;i){Gizmos.DrawSphere(corners[i],0.1f);}4.TestPlanesPoint作用测试单个点是否在平面组围成的凸空间内部和TestPlanesAABB对应适合点级别的可见性/空间判断。方法说明publicstaticboolTestPlanesPoint(Plane[]planes,Vector3point);返回true点在凸空间内部返回false点在空间外部示例// 判断某个点比如敌人的位置是否在相机可见范围内Plane[]frustumGeometryUtility.CalculateFrustumPlanes(Camera.main);boolisPointInViewGeometryUtility.TestPlanesPoint(frustum,enemy.position);5.CreatePlane作用程序化快速生成指定大小、分段的平面网格数据适合快速原型开发、程序化生成平面。方法说明// 常用重载默认生成XZ平面publicstaticMeshCreatePlane(floatwidth,floatheight,intwidthSegments,intheightSegments);// 带轴向参数的重载publicstaticMeshCreatePlane(floatwidth,floatheight,intwidthSegments,intheightSegments,PlaneAxisplaneAxis);planeAxis可选值XZ/XY/YZ指定平面所在的坐标系平面示例// 一键生成10x10单位、10x10分段的XZ平面MeshplaneMeshGeometryUtility.CreatePlane(10f,10f,10,10);GetComponentMeshFilter().meshplaneMesh;6.ProjectPoints作用对一组3D点做投影变换将点从原空间变换到裁剪空间适合自定义投影、裁剪逻辑开发。方法说明publicstaticvoidProjectPoints(Vector3[]points,Matrix4x4projectionMatrix,floatnearClip,floatfarClip,Vector2[]projectedPositions);传入原3D点和投影矩阵通常是相机的世界到投影空间矩阵输出变换后的二维投影坐标。整体注意事项所有方法都是静态无状态运行时调用性能开销很低可放心用于帧更新逻辑所有涉及空间坐标的方法都需要保持空间一致性比如平面是世界空间待测试的点/包围盒也需要转成世界空间再传入。