UMiniGame/Assets/Games/Scripts/Tools/VisibilityTool.cs
2025-12-27 15:29:20 +08:00

37 lines
1.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class VisibilityTool
{
/// <summary>
/// 判断对象是否在相机视锥体内
/// </summary>
/// <param name="obj">目标对象需带有Renderer组件</param>
/// <param name="camera">目标相机</param>
/// <returns>是否可视</returns>
public static bool IsObjectInFrustum(GameObject obj, Camera camera)
{
if (obj == null || camera == null) return false;
//Renderer renderer = obj.GetComponent<Renderer>();
//if (renderer == null) return false; // 没有Renderer则无法获取包围盒
Vector3 viewportPos = camera.WorldToViewportPoint(obj.transform.position);
bool isVisible = viewportPos.x >= 0 && viewportPos.x <= 1 &&
viewportPos.y >= 0 && viewportPos.y <= 1 &&
viewportPos.z > 0;
return isVisible;
//var extents = renderer.bounds.extents;
//if (extents.x < 0.001 && extents.y < 0.001 && extents.z < 0.001)
//{
// renderer.bounds = new Bounds(renderer.bounds.center, Vector3.one);
//}
//// 获取相机的视锥体平面数组
//Plane[] frustumPlanes = GeometryUtility.CalculateFrustumPlanes(camera);
//// 检测包围盒是否在视锥体内
//return GeometryUtility.TestPlanesAABB(frustumPlanes, renderer.bounds);
}
}