-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
72 additions
and
8 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
using UnityEngine; | ||
|
||
namespace Environment | ||
{ | ||
[RequireComponent(typeof(Camera))] | ||
public sealed class FrustumCulling : MonoBehaviour | ||
{ | ||
private const string CULL_ABLE_TAG = "Cullable"; | ||
|
||
private GameObject[] _cullAbleObjects; | ||
private Renderer[] _cachedRenderers; | ||
private Camera _this; | ||
|
||
private void Awake() => _this = GetComponent<Camera>(); | ||
|
||
private void Start() => InitCullingObjects(); | ||
|
||
private void Update() => UpdateCullAbles(); | ||
|
||
private void InitCullingObjects() | ||
{ | ||
_cullAbleObjects = GameObject.FindGameObjectsWithTag(CULL_ABLE_TAG); | ||
_cachedRenderers = new Renderer[_cullAbleObjects.Length]; | ||
int length = _cullAbleObjects.Length; | ||
|
||
for (int i = 0; i < length; i++) | ||
{ | ||
_cachedRenderers[i] = _cullAbleObjects[i].GetComponent<Renderer>(); | ||
} | ||
} | ||
|
||
private void UpdateCullAbles() | ||
{ | ||
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(_this); | ||
int length = _cullAbleObjects.Length; | ||
|
||
for (int i = 0; i < length; i++) | ||
{ | ||
bool isVisible = GeometryUtility.TestPlanesAABB(planes, _cachedRenderers[i].bounds); | ||
|
||
OcclusionCulling(ref isVisible, i); | ||
|
||
_cullAbleObjects[i].SetActive(isVisible); | ||
} | ||
} | ||
|
||
private void OcclusionCulling(ref bool isVisible, int i) | ||
{ | ||
if (!isVisible) | ||
return; | ||
|
||
Vector3 direction = _cullAbleObjects[i].transform.position - _this.transform.position; | ||
float distance = direction.magnitude; | ||
RaycastHit hit; | ||
|
||
if (Physics.Raycast(_this.transform.position, direction, out hit, distance) | ||
&& hit.transform != _cullAbleObjects[i].transform) | ||
isVisible = false; | ||
} | ||
} | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.