【问题标题】:how to limit CreateCell c# procedural grid generation unity如何限制CreateCell c#程序网格生成统一
【发布时间】:2017-03-28 11:37:59
【问题描述】:

我正在学习 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)

我已经在地平面下方创建了一个菱形的平面。

脚本如下。

公共类 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();
}
}

到目前为止的网格

【问题讨论】:

    标签: c# unity3d procedural-generation


    【解决方案1】:

    一个快速的解决方案是在创建单元格的代码部分之前添加一个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);
                    }
                }
           }
       }
    }
    

    【讨论】:

    • public int tempY; int 'TempY = height' and 'if (x + y 创建了我所追求的解决方案。谢谢@Hristo
    猜你喜欢
    • 2021-09-24
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 2017-01-26
    • 2018-12-01
    • 2018-05-29
    相关资源
    最近更新 更多