[SOLVED] Check if gameobject without renderer is within camera view
I have a camera that looks down towards the player.
I have alot of Vector3 positions that is placeholders for pooled gameobjects.
When 1 or more of these positions are within a certain distance from the camera view I want to activate the pooled gameobjects and move them to those locations so they will be visible to the player.
I know how to activate and deactivate and all that but I cant seem to figure out how to make the camera know when the positions are in view.
I can not use OnBecameVisible
or OnBecameInvisible
as I only have locations and no renderer at the locations until the pooled objects are moved to those locations.
Do anyone know how to do this or any ideas that may help?
Answer by Hellium · Oct 07, 2019 at 05:17 AM
You can test if the object is within the camera frustum:
using UnityEngine;
public class Example
{
Transform t;
Camera cam;
Plane[] planes;
void Start()
{
cam = Camera.main;
}
void Update()
{
// Move this line to `Start` if the camera does not move / rotate
planes = GeometryUtility.CalculateFrustumPlanes(cam);
if (GeometryUtility.TestPlanesAABB(planes, new Bounds(t.position, Vector3.zero))
{
Debug.Log(t.name + " has been detected!");
}
else
{
Debug.Log("Nothing has been detected");
}
}
}
Source: https://docs.unity3d.com/ScriptReference/GeometryUtility.TestPlanesAABB.html
Thanks, I will check this out today to see if it works for me :)
Did not get it to work. But I found a way :) Code will be down below :)
Answer by Inferi · Oct 07, 2019 at 03:25 PM
[SOLVED] I got this to work :)
In Update:
if(IsVisible(transform.position, transform.GetComponent<Collider>().bounds.size, Global.MainCamera)) {
for(int i = 0; i < GlobalPoolingGrass.GrassList.Count; i++) {
if(!GlobalPoolingGrass.GrassList[i].activeInHierarchy) {
if(i == m_grassPosition.Count) {
break;
} else {
GlobalPoolingGrass.GrassList[i].transform.position = m_grassPosition[i];
GlobalPoolingGrass.GrassList[i].transform.rotation = new Quaternion(0f, m_grassRotation[i], 0f, 0f);
GlobalPoolingGrass.GrassList[i].SetActive(true);
break;
}
}
}
}
And the Function "IsVisible" Not created by me
bool IsVisible(Vector3 pos, Vector3 boundSize, Camera camera) {
var bounds = new Bounds(pos, boundSize);
var planes = GeometryUtility.CalculateFrustumPlanes(camera);
return GeometryUtility.TestPlanesAABB(planes, bounds);
}