c# - 如何检测相机 FOV 内的所有游戏对象? Unity3D

标签 c# unity3d scripting camera frustum

我想检测所有由“Wall_[0-24]”标记的游戏对象,它们在相机 FOV 内。我已经尝试过 Raycasting,但因为它只是一条光线,所以它不会同时捕捉到多个物体。 我试过这个:

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!");
        }
    }
}

我得到的只是每一面墙一次又一次 - 并不真正取决于相机的位置。当我的相机沿着特定路径移动时,可见的墙壁应该会发生变化。在图像中,绿色部分可见,红色部分不再(因为相机已经通过它们)。 explaining what should be output as a visible wall

那么我如何通过这个特定的相机实现所有看到的墙壁的输出

感谢您的帮助!

最佳答案

使用 Draco18s 的 answer ,下面是如何实现他所说的。

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

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;
    }
}

关于c# - 如何检测相机 FOV 内的所有游戏对象? Unity3D,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45020915/

相关文章:

c# - 长度为 1 的数组是否与同一类型的单个变量大小相同?

c# - 如何禁用鼠标单击时的对象控制?

git: repo 监控工具

c# - OnMouseOver() 不适用于 child

c# - Unity 和 System.Drawing on OS X

powershell - 观察本地文件夹的变化并将它们上传到 SFTP 服务器

hadoop - pig 脚本: count returns 0 on null field

c# - 将一个整数表示为其他一些固定整数的总和

c# - 更好地掌握接口(interface)

c# - 我怎样才能在 c# 中正确地做到这一点(压缩代码)