Unity 检测对象是否在相机的视锥体范围内
TestInCamera.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Stopwatch = System.Diagnostics.Stopwatch;
[RequireComponent(typeof(MeshRenderer))]
public class TestInCamera : MonoBehaviour {
private Camera m_cam;
private MeshRenderer m_meshRenderer;
private Stopwatch m_sw;
private void Start() {
m_cam = Camera.main;
m_meshRenderer = GetComponent<MeshRenderer>();
// 采用给定摄像机的视椎体,然后返回形成此视椎体的六个平面。
// 排序:[0] = 左、[1] = 右、[2] = 下、[3] = 上、[4] = 近、[5] = 远
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(m_cam);
for (int i = 0; i < 6; ++i) {
GameObject p = GameObject.CreatePrimitive(PrimitiveType.Plane);
p.name = "Plane " + i.ToString();
p.transform.position = -planes[i].normal * planes[i].distance;
p.transform.rotation = Quaternion.FromToRotation(Vector3.up, planes[i].normal);
}
}
void Update() {
if (m_sw == null) {
m_sw = new Stopwatch();
}
m_sw.Restart();
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(m_cam);
bool inside = GeometryUtility.TestPlanesAABB(planes, m_meshRenderer.bounds);
m_sw.Stop();
//Debug.Log($"time:{m_sw.ElapsedMilliseconds} ms, inside:{inside}");
}
}