如何检测相机FOV中的所有GameObject? Unity3D [英] How to detect all GameObjects within the Camera FOV? Unity3D

查看:156
本文介绍了如何检测相机FOV中的所有GameObject? Unity3D的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检测所有标记为"Wall_ [0-24] "的游戏对象,它们位于摄像机FOV内.我已经尝试过光线投射,但是由于它只有一条光线,因此不会同时捕获多个对象. 我尝试过这个:

I would like to detect all gameobjects tagged by "Wall_[0-24]", which are within the camera FOV. I already tried Raycasting, but as it is only one ray, it doesn't catch multiple objects at the same time. I tried this one:

void Update() {
    GameObject walls = GameObject.FindGameObjectWithTag ("Wall");
    Renderer[] renders = walls.GetComponentsInChildren<Renderer> ();

    for (int i = 1; i < renders.Length; i++) {
        if (walls.GetComponentInChildren<Renderer> ().isVisible) {
            Debug.Log (renders[i] + " is detected!");
        } else {
            Debug.Log ("Nothing's detecetd!");
        }
    }
}

我得到的只是一遍又一遍的墙-并不真正取决于相机的位置.当我的相机沿着某个路径行驶时,可见的墙壁应会改变.在图像中,绿色部分可见,而红色部分不再(因为相机已经通过了它们).

All I get is every wall again and again - doesn't really depend on the camera's position. As my camera follows a certain path, the visible walls should change. In the image the green part is visible and the red one not anymore (because the camera already passed them).

那么如何通过此特定摄像机实现所有可见墙壁的输出?

So how could I realize the output of all seen walls by this specific camera?

谢谢您的帮助!

推荐答案

使用Draco18s的 answer ,下面是如何贯彻他说的话.

Using Draco18s' answer, below is how to implement what he said.

创建一个新脚本并将其命名为CheckWalls并附加以下代码

Create a new Script and name it CheckWalls and attach the below code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CheckWalls : MonoBehaviour
{
    Renderer[] renderers;

    void Awake ()
    {
        GameObject walls = GameObject.FindGameObjectWithTag ("Wall");
        renderers = walls.GetComponentsInChildren<Renderer> ();
    }

    void Update() 
    {
        OutputVisibleRenderers(renderers);
    }

    void OutputVisibleRenderers (Renderer[] renderers)
    {
        foreach (var renderer in renderers)
        {
            // output only the visible renderers' name
            if (IsVisible(renderer)) 
            {
                Debug.Log (renderer.name + " is detected!");    
            }           
        }

        Debug.Log ("--------------------------------------------------");
    }

    private bool IsVisible(Renderer renderer) 
    {
        Plane[] planes = GeometryUtility.CalculateFrustumPlanes(Camera.main);

        if (GeometryUtility.TestPlanesAABB(planes , renderer.bounds))
            return true;
        else
            return false;
    }
}

这篇关于如何检测相机FOV中的所有GameObject? Unity3D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆