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来判断当前位置的瓦片是否为草地,如果否,则再次寻找。
最终效果:
注意事项
一定要绑定瓦片和瓦片地图,否则会报错!!!
热门推荐
如何提升房间门的隔音效果?有哪些方法可以有效降低噪音传播?
电力系统中常用通信协议概述
抢夺罪犯罪的特点:从法律实务视角的全面解读
4个方法识别被害妄想症:从行为到情绪的全面评估
B站粉丝量排行榜解析:影响因素与未来趋势
你被“雷”到的概率有多高,如何能安全避免雷击呢?
痛风为何找上年轻人?科学预防痛风有妙招
大量吃橘子、嗑瓜子、喝饮料……“上火”了如何缓解?
从古代到现代:成都作为四川首府的来龙去脉
心理学“第一次效应”:分手后,这就是你忘不掉前任的原因
中东国家如何挖掘蓝色经济潜力?三个国家的实践案例
房东强制要求租客搬离合理吗
房屋拆迁时租客权益保护指南
清远英德出名的茶品种及产地介绍
F-35新型机载光电瞄准系统(EOTS)工作原理分析
做期货为何会出现亏损?如何降低期货投资的风险?
桂圆米糕粥温养胃气 零厨艺也能轻松上手的3步骤食谱大公开!
专家解答:梨状肌综合征能通过锻炼治疗吗?
人到晚年,不管你有多少存款,都要帮儿女这“3种忙”,比钱重要!
家庭教育 | 关于家庭教育的9点建议
10 场最具代表性的动漫女性角色打斗
跟着地铁玩转昆明 | 4号线的景点等你来!
昆明地铁新动态:市民的期待与官方的回应
摄影技巧文字介绍:从心开始,用文字点亮摄影艺术
为什么要实行普遍食盐加碘?减盐与补碘的关系是什么?
6个跑步前热身和跑步后拉筋动作|运动达人分享如何避免跑伤和肌肉酸痛
《名侦探柯南》完结遥遥无期:青山刚昌透露继续连载时间仍需较长
道氏技术:预计2024年上半年盈利8800万元-1.32亿元 同比扭亏
因势利导,让AI技术赋能教育健康发展
人参芦头的特征与年份判断指南