如何限制 CreateCell c# procedural grid generation unity

how to limit CreateCell c# procedural grid generation unity

我正在为统一学习 C#,可以使用一些指导。

我正在学习 catlikecoding 十六进制地图教程,但我已经根据自己的方式修改了网格。

http://catlikecoding.com/unity/tutorials/hex-map-1/

我的目标是从 7 * 7 网格开始按程序创建正方形金字塔。我用的是预制飞机

如何限制 CreateCell 循环函数,以便在满足以下表达式时不创建具有 (x,y) 坐标的单元格

x + y > n - 1 where n = grid size (for example (6,1) or (5,6)

我已经创建了一个菱形平面,不需要的平面位于地平面下方。

脚本如下

public class HexGrid:MonoBehaviour {

public int width = 7;
public int height = 7;
public int length = 1;


public SquareCell cellPrefab;
public Text cellLabelPrefab;

SquareCell[] cells;

Canvas gridCanvas;

void Awake () {
    gridCanvas = GetComponentInChildren<Canvas>();

    cells = new SquareCell[height * width * length];

    for (int z = 0 ; z < height; z++) {
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < length; y++)
                CreateCell(x, z, y);
        }
    }
}

void CreateCell(int x, int z, int y) {
    Vector3 position;
    position.x = x * 10f ;
    position.y = ((y + 1) - (x + z)) * 10f + 60f;
    position.z = z * 10f ;

    Cell cell = Instantiate<Cell>(cellPrefab);
    cell.transform.SetParent(transform, false);
    cell.transform.localPosition = position;

    Text label = Instantiate<Text>(cellLabelPrefab);
    label.rectTransform.SetParent(gridCanvas.transform, false);
    label.rectTransform.anchoredPosition =
        new Vector2(position.x, position.z);
    label.text = x.ToString() + "\n" + z.ToString();
}
}

到目前为止的网格

一个快速的解决方案是在创建单元格的代码部分之前添加一个 if 语句。在这种情况下,方法 CreateCell()。该 if 语句应该在代码中包含您的逻辑。您还必须为要检查的大小创建两个变量。例如:

public int tempX;
public int tempY;
void Awake () {
gridCanvas = GetComponentInChildren<Canvas>();

cells = new SquareCell[height * width * length];

for (int z = 0 ; z < height; z++) {
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < length; y++)
            {
                if (x + y < (tempX + tempY) - 1)
                {
                    CreateCell(x, z, y);
                }
            }
       }
   }
}