您的位置:首页 > 移动开发 > Unity3D

001【2D Rougelike】随机地图的生成

2017-06-17 23:31 316 查看
简单思路:
指定范围内,在随机位置生成随机数量的随机图块。
①指定范围&随机位置:获取需要图块生成的位置坐标,存放在一个二维List中;
②随机图块:各类图块(Prefab)按类型存放在不同数组中,以便随机调用;
③随机数量:定义图块的最小值和最大值,在此区间内取随机数。
④各个图块在生成时不会互相叠加,即不会生成在同一位置。

实现方法:

//① 指定范围&随机位置
private int col=10;
private int rows=10;                                                          //首先定义地图总行数和列数

private List<Vector2> positionList=new List<Vector2>();  //用于存放坐标

for(x=2;x<col-2;x++) {                                              //遍历需要生成图块的所有坐标,存放到List中。
for(y=2;y<row-2;y++){
positionList.Add(new Vector2(x,y));
}
}
//取得随机位置的方法
private Vector2 randomPosition();{
int positionIndex=Random.Range(0,positionList.Length);//在List中随机取得
Vector2 pos=Vector2 positionList[positionIndex];
positionList.RemoveAt(positionIndex);  //取过的位置从List中移除
retrun pos;
}
//取得随机图块同理。
②生成随机图块的通用方法
private void InstantiateItems(int count,GameObject[] prefabs){
Vector2 pos=randomPosition();//调用方法,取随机位置;
GameObject prefab=randomPrefab(prefabs);//调用方法,取随机图块,并且参数为需要的prefab
GameObject go=GameObject.Instantiate(prefab,pos,Quaternion.identity)as GameObject;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Unity