所以我正在开发一个使用坐标系的游戏,我想用一定数量的树填充地图。我这样做的方式(可能不是最好的方法)是选择一组随机坐标,检查这些坐标是否在其中包含树的位置列表中,如果没有将树添加到映射,并将这些坐标添加到列表中。我的直觉是将坐标存储为数组,但我似乎无法弄清楚它的语法。这就是我所拥有的:
int boardWidth = 10;
int boardHeight = 10;
int numTrees = 75;
List<int[]> hasTree = new List<int[]>();
public Transform tree;
Transform[,] SetTrees(Transform[,] map) {
int treex = Random.Range(0,boardWidth-1);
int treey = Random.Range(0,boardHeight-1);
int[] treeCoords = new int[] { treex,treey };
int treeCount = 0;
while(treeCount < numTrees){
if (hasTree.Contains(treeCoords)){
treex = Random.Range(0,boardWidth-1);
treey = Random.Range(0,boardHeight-1);
}
else{
map[treex,treey] = (Transform)Instantiate(tree, new Vector3(i*tileWidth, 10, j*tileHeight), Quaternion.AngleAxis(90, Vector3.left));
hasTree.Add(treeCoords);
treex = Random.Range(0,boardWidth-1);
treey = Random.Range(0,boardHeight-1);
treeCount++;
}
}
return(map);
}
有什么想法吗?
答案 0 :(得分:3)
如果我是你,我会尝试这样的事情:
int boardWidth = 10;
int boardHeight = 10;
int numTrees = 75;
var rnd = new Random();
var query =
from x in Enumerable.Range(0, boardWidth)
from y in Enumerable.Range(0, boardHeight)
orderby rnd.NextDouble()
select new { x, y };
var board = new bool[boardWidth, boardHeight];
foreach (var pair in query.Take(numTrees))
{
board[pair.x, pair.y] = true;
}
答案 1 :(得分:0)
保持简单愚蠢:
Transform[,] SetTrees(Transform[,] map) {
for(int treeCount = 0; treeCount < numTrees; treeCount++){
int treex = Random.Range(0,boardWidth-1);
int treey = Random.Range(0,boardHeight-1);
map[treex,treey] = new TreeTransform(treex, treey}
}
return(map);
}
将Tree创建的细节隐藏在它所属的构造函数TreeTransform中。
谁在乎董事会树木的创作顺序?没用。
没有理由确保树的数量是精确的,所以只需忽略重复。
答案 2 :(得分:0)
简化代码,然后可能更容易确定您的最佳行动方案。 我通过分解问题来简化,直到它如此简单,我无法真正看到如何做到这一点!!!
我在猜这些代码是如何工作的,但我想你想要这样的东西......
Transform[,] SetTrees(Transform[,] map) {
for (int i = 0; i < numTrees; i++){
if(!AddTreeTo(map)){
--i;
}
}
return(map);
}
bool AddTreeToMap(Transform[,] map)
{
int[] treeCoord = GetRandomCoord(map.Width, map.Height);
if (!map[treeCoord[0],treeCoord[1]].HasTree()){
map[treex,treey] = (Transform)Instantiate(tree, new Vector3(i*tileWidth, 10, j*tileHeight), Quaternion.AngleAxis(90, Vector3.left));
map[treeCoord[0],treeCoord[1]].Add(treeCoords);
return true;
}
return false;
}
int[] GetRandomTreeCoord(int maxX, int maxY)
{
int treex = Random.Range(0,maxX-1);
int treey = Random.Range(0,maxY-1);
int[] treeCoords = new int[] { treex,treey };
return treeCoords;
}