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<MeshFilter>();
meshRenderer = GetComponent<MeshRenderer>();
meshCollider = GetComponent<MeshCollider>();
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<MeshFilter>();
for (int i = 0; i < filters.Length; i++)
{
filters[i].gameObject.AddComponent<MeshCollider>().sharedMesh = filters[i].mesh;
}
//保存渲染器用于视锥体剪裁
renderers = renderers.Concat(fit.GetComponentsInChildren<Renderer>()).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;
}
}
}
简易地形生成+视锥体剪裁
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...