using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TerrainGenerator : MonoBehaviour
{
public int depth = 20;
public int width = 256;
public int height = 256;
public float scale = 20f;
public float offsetX = 200f;
public float offsetY = 200f;
public float velocity = 5f;
private void Start()
{
offsetX = Random.Range(0f, 99999f);
offsetY = Random.Range(0f, 99999f);
}
// Start is called before the first frame update
void Update()
{
Terrain terrain = GetComponent<Terrain>();
terrain.terrainData = GenerateTerrain(terrain.terrainData);
offsetX += velocity * Time.deltaTime;
}
TerrainData GenerateTerrain(TerrainData terrainData)
{
terrainData.heightmapResolution = width + 1;
terrainData.size = new Vector3(width, depth, height);
terrainData.SetHeights(0, 0, GenerateHeights());
return terrainData;
}
float[,] GenerateHeights()
{
float[,] heights = new float[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
heights[x, y] = CalculateHeight(x, y);
}
}
return heights;
}
float CalculateHeight(int x, int y)
{
float xCoord = (float)x / width * scale + offsetX;
float yCoord = (float)y / height * scale + offsetY;
return Mathf.PerlinNoise(xCoord, yCoord);
}
}
基础逻辑:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeGenerator : MonoBehaviour
{
// 长方体长宽高 最大值
public int depth = 20;
public int width = 256;
public int height = 256;
// 控制移动速度
public float velocity = 5f;
//public float offsetX = 200f;
//public float offsetY = 200f;
// 间隔过长时间生成物体
private float timer = 1f;
private float time = 0f;
// 生成物体集合
List<Transform> cubeList = new List<Transform>();
private void Start()
{
//offsetX = Random.Range(0f, 99999f);
//offsetY = Random.Range(0f, 99999f);
}
void Update()
{
time += Time.deltaTime;
// 满足条件生成物体
//if (Input.GetKeyDown(KeyCode.A))
// 每秒生成一个物体
if(time - timer >= 0)
{
Transform terrain = CreateCube();
cubeList.Add(terrain);
time = 0;
}
// 物体移动
for (int i = 0; i < cubeList.Count; i++)
{
cubeList[i].Translate(Vector3.forward * velocity * Time.deltaTime);
}
}
// 创建物体
Transform CreateCube()
{
// 创建Cube
Transform cubeTrans = GameObject.CreatePrimitive(PrimitiveType.Cube).transform;
//Instantiate(gameobjectPrefabs);
cubeTrans.localPosition = Vector3.zero;
// 随机大小
cubeTrans.localScale = new Vector3(Random.Range(0.1f, width), Random.Range(0.1f, depth), Random.Range(0.1f, height));
return cubeTrans;
}
}