简易地形生成+视锥体剪裁

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

public class CreatWord : MonoBehaviour
{
    public GameObject[] prefabs;
    public Color color = Color.white;
    public int num = 20;
    public float scale = 10;
    MeshFilter meshFilter;
    MeshRenderer meshRenderer;
    MeshCollider meshCollider;
    //视锥体裁剪用
    Renderer[] renderers;
    Camera mainCamera;
    Plane[] planes;
    // Start is called before the first frame update
    void Start()
    {
        renderers = new Renderer[0];
        planes = new Plane[6];
        mainCamera = Camera.main;
        //网格
        meshFilter = GetComponent();
        meshRenderer = GetComponent();
        meshCollider = GetComponent();
        VertexHelper vh = new VertexHelper();
        for (int x = 0; x < num; x++)
        {
            for (int z = 0; z < num; z++)
            {
                float y = Mathf.PerlinNoise(x * 0.1f, z * 0.1f);
                Vector3 pos = new Vector3((x - num / 2) * scale, y * scale - scale / 2, (z - num / 2) * scale);
                vh.AddVert(pos, color, new Vector2((float)x / num, (float)z / num));

                //随机创建建筑物
                if (x % 2 == 0 && z % 2 == 0 && Random.Range(0, 10) < 5)
                {
                    GameObject fit = Instantiate(prefabs[Random.Range(0, prefabs.Length)], pos - Vector3.up, Quaternion.identity, transform);

                    MeshFilter[] filters = fit.GetComponentsInChildren();
                    for (int i = 0; i < filters.Length; i++)
                    {
                        filters[i].gameObject.AddComponent().sharedMesh = filters[i].mesh;
                    }
                    //保存渲染器用于视锥体剪裁
                    renderers = renderers.Concat(fit.GetComponentsInChildren()).ToArray();
                }
            }
        }
        for (int x = 0; x < num - 1; x++)
        {
            for (int z = 0; z < num - 1; z++)
            {
                vh.AddTriangle(x * num + z, x * num + z + 1, (x + 1) * num + z + 1);
                vh.AddTriangle(x * num + z, (x + 1) * num + z + 1, (x + 1) * num + z);
            }
        }
        Mesh mesh = new Mesh();
        vh.FillMesh(mesh);
        meshFilter.mesh = mesh;
        StaticBatchingUtility.Combine(gameObject);
        meshCollider.sharedMesh = mesh;
    }
    public void Look()
    {
        //视锥体裁剪
        GeometryUtility.CalculateFrustumPlanes(mainCamera, planes);
        for (int i = 0; i < renderers.Length; i++)
        {
            var bounds = renderers[i].bounds;
            var result = GeometryUtility.TestPlanesAABB(planes, bounds);
            renderers[i].enabled = result;
        }
    }
}

你可能感兴趣的:(简易地形生成+视锥体剪裁)