我正在尝试使用 Unity 3D 和 C# 实现 Conway 的生命游戏......但不知何故我无法让我的算法完成这些模式中的任何一个:
当我尝试遵循某些模式时,会发生以下情况:
这是代码负责人:
public List<GameObject> GetNeighbors(GameObject cell) {
List<GameObject> neighbors = new List<GameObject>();
Vector2 cellPosition = cell.transform.position;
for (int x = Mathf.RoundToInt(cellPosition.x) - 1; x <= Mathf.RoundToInt(cellPosition.x) + 1; x++) {
for (int y = Mathf.RoundToInt(cellPosition.y) - 1; y <= Mathf.RoundToInt(cellPosition.y) + 1; y++) {
if (x == Mathf.RoundToInt(cellPosition.x) && y == Mathf.RoundToInt(cellPosition.y))
continue;
if (x < 0 || x >= gridSize.x || y < 0 || y >= gridSize.y)
continue;
neighbors.Add(cells[x, y]);
}
}
return neighbors;
}
public void UpdateGrid() {
foreach (GameObject cell in cells) {
// Less than 2 neighbors, die by underpopulation
// More than 3 neighbors, die by overpopulation
// Exactly 3 neighbors, become alive
// Exactly 2 or 3 neighbors, stay alive
int aliveNeighbors = 0;
foreach (GameObject neighbor in GetNeighbors(cell)) {
if (neighbor.GetComponent<CellBehaviour>().isAlive)
aliveNeighbors++;
}
if (cell.GetComponent<CellBehaviour>().isAlive) {
if (aliveNeighbors < 2 || aliveNeighbors > 3)
cell.GetComponent<CellBehaviour>().SetAlive(false);
} else {
if (aliveNeighbors == 3)
cell.GetComponent<CellBehaviour>().SetAlive(true);
}
}
}
有什么想法/建议可以实施吗?在过去的几个小时里,我一直在努力寻找错误。
我正在将我的结果与这个站点进行比较