Unity引擎通过柏林噪声生成无限随机地图并生成资源(区块化)
创作时间:
作者:
@小白创作中心
Unity引擎通过柏林噪声生成无限随机地图并生成资源(区块化)
引用
CSDN
1.
https://blog.csdn.net/WsAzQwQ/article/details/141155247
本文将介绍如何使用Unity引擎通过柏林噪声(Perlin Noise)生成无限随机地图,并在地图上生成资源(如树木)。这种方法采用区块化(Chunk-based)的方式,可以有效提高性能并实现无缝加载。
代码实现
先上代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class InfiniteMapGenerator : MonoBehaviour
{
// Start is called before the first frame update
public int chunkSize = 16;
public float scale = 0.1f;
public Tilemap tilemap;
public Tile[] tiles;
public GameObject treePrefab;
public Transform playerTransform;
private Dictionary<Vector2Int, bool> activeChunks = new Dictionary<Vector2Int, bool>();
private Dictionary<Vector2Int, List<Vector3>> chunkTreePositions = new Dictionary<Vector2Int, List<Vector3>>();
private Dictionary<Vector2Int, List<GameObject>> chunkTrees = new Dictionary<Vector2Int, List<GameObject>>();
private Vector2Int currentChunk = new Vector2Int(0, 0);
private int seed;
void Start()
{
seed = Random.Range(0, 100001);
Random.InitState(seed);
// 找到一个合适的起始位置
Vector3 startPosition = FindSuitableStartPosition();
playerTransform.position = startPosition;
// 初始化当前块
currentChunk = new Vector2Int(Mathf.FloorToInt(startPosition.x / chunkSize), Mathf.FloorToInt(startPosition.y / chunkSize));
UpdateChunks();
}
void Update()
{
Vector3 playerPosition = playerTransform.position;
Vector2Int playerChunk = new Vector2Int(Mathf.FloorToInt(playerPosition.x / chunkSize), Mathf.FloorToInt(playerPosition.y / chunkSize));
if (playerChunk != currentChunk)
{
currentChunk = playerChunk;
UpdateChunks();
}
}
void UpdateChunks()
{
List<Vector2Int> chunksToRemove = new List<Vector2Int>();
foreach (var chunk in activeChunks)
{
if (Mathf.Abs(chunk.Key.x - currentChunk.x) > 1 || Mathf.Abs(chunk.Key.y - currentChunk.y) > 1)
{
chunksToRemove.Add(chunk.Key);
}
}
foreach (var chunk in chunksToRemove)
{
ClearChunk(chunk);
activeChunks.Remove(chunk);
}
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
Vector2Int chunkPos = new Vector2Int(currentChunk.x + x, currentChunk.y + y);
if (!activeChunks.ContainsKey(chunkPos))
{
GenerateChunk(chunkPos);
activeChunks.Add(chunkPos, true);
}
else
{
EnableChunkTrees(chunkPos);
}
}
}
}
void GenerateChunk(Vector2Int chunkPos)
{
List<Vector3> treePositions = new List<Vector3>();
for (int x = 0; x < chunkSize; x++)
{
for (int y = 0; y < chunkSize; y++)
{
int worldX = chunkPos.x * chunkSize + x;
int worldY = chunkPos.y * chunkSize + y;
float perlinValue = Mathf.PerlinNoise(seed + worldX * scale, seed + worldY * scale);
Tile tile = GetTileFromPerlinValue(perlinValue);
tilemap.SetTile(new Vector3Int(worldX, worldY, 0), tile);
if (perlinValue > 0.4f)
{
if (Random.value < 0.1f)
{
treePositions.Add(new Vector3(worldX, worldY, 0));
}
}
}
}
chunkTreePositions.Add(chunkPos, treePositions);
chunkTrees.Add(chunkPos, new List<GameObject>());
}
void ClearChunk(Vector2Int chunkPos)
{
if (chunkTrees.ContainsKey(chunkPos))
{
foreach (var tree in chunkTrees[chunkPos])
{
Destroy(tree);
}
chunkTrees.Remove(chunkPos);
}
if (chunkTreePositions.ContainsKey(chunkPos))
{
chunkTreePositions.Remove(chunkPos);
}
for (int x = 0; x < chunkSize; x++)
{
for (int y = 0; y < chunkSize; y++)
{
int worldX = chunkPos.x * chunkSize + x;
int worldY = chunkPos.y * chunkSize + y;
tilemap.SetTile(new Vector3Int(worldX, worldY, 0), null);
}
}
}
void EnableChunkTrees(Vector2Int chunkPos)
{
if (chunkTreePositions.ContainsKey(chunkPos))
{
foreach (var position in chunkTreePositions[chunkPos])
{
GameObject tree = Instantiate(treePrefab, position, Quaternion.identity);
chunkTrees[chunkPos].Add(tree);
}
chunkTreePositions.Remove(chunkPos);
}
}
Tile GetTileFromPerlinValue(float perlinValue)
{
if (perlinValue < 0.4f)
{
return tiles[0];
}
else
{
return tiles[1];
}
}
Vector3 FindSuitableStartPosition()
{
Vector3 startPosition;
do
{
int x = Random.Range(-chunkSize * 5, chunkSize * 5);
int y = Random.Range(-chunkSize * 5, chunkSize * 5);
float perlinValue = Mathf.PerlinNoise(seed + x * scale, seed + y * scale);
if (perlinValue > 0.4f)
{
startPosition = new Vector3(x, y, 0);
break;
}
} while (true);
return startPosition;
}
}
功能分析
通过瓦片地图和柏林噪声来实现此功能,将有此代码的脚本绑定在摄像机中,并设置为Player的子项。
我添加了一个 chunkTrees
字典来跟踪每个区块中的Tree。在生成区块时,将Tree的实例存在 chunkTrees
字典中,并在需要时启用或禁用它们。这样可以确保Tree只在玩家进入区块时才被启用,离开时被禁用,从而提高性能。(生成Tree的概率为0.1,可以自己调整,区块大小也可以调整)
同时,为了防止玩家出生在水中(蓝色),我用perlinValue来判断当前位置的瓦片是否为草地,如果否,则再次寻找。
最终效果:
注意事项
一定要绑定瓦片和瓦片地图,否则会报错!!!
热门推荐
野生乌龟汤:滋补界的顶流,但请合法食用
地暖安装注意事项及常见问题解答
地暖供水温度标准及解决地暖不热问题的方法
河鲜中藏着不少嘌呤“大户”!痛风患者该怎样“聪明”吃“鲜”?
2024版「痛风饮食指南」重磅发布!附300种食物嘌呤含量表
从曾国藩家训看现代家庭教育:传统智慧的现代价值
优良家风:塑造孩子健康心理的无形力量
现代家风家规:传承与创新的交响曲
家风家规:家庭和谐的基石
揭秘禅式思维:如何用禅式思维认识世界?
王维诗画双绝,其著名的山水田园诗又是如何展现“空”与“有”
王维《归辋川作》中的归隐情怀与人生哲思
经典古井贡:收藏家必知的鉴别秘籍
唐朝十大山水田园诗人排行榜,柳宗元仅排第四,谁能排第一?
山水田园诗:中国古代诗歌中的田园牧歌
欧冠最新夺冠赔率:利物浦巴萨排前二,曼城拜仁难进前十?
原木期货上市首日成交近10万手 房地产需求预期成市场焦点
原木期货涨停!供需紧张叠加政策利好,这轮行情能走多远?
秋冬防鼻窦炎,这些水果蔬菜要多吃!
逐渊汤治疗鼻窦炎:效果如何?
鼻窦炎患者的日常护理全攻略:从饮食到生活,这些妙招帮你轻松应对
农夫山泉促销大战:钟睒睒如何应对娃哈哈挑战?
智能道闸如何重塑社区安全与管理新生态
智能道闸:从功能到安装的全面指南
从《诗经》到陆游:古人用“聿”字作诗的智慧
“聿”字背后的文化传承故事
颜真卿笔下的“聿”:从《多宝塔碑》到《颜勤礼碑》
你家娃会写“聿”字吗?来挑战一下!
冬日张掖摄影指南:捕捉最美冰雪瞬间
七彩丹霞:甘肃最美打卡地