SpriteKit创建迷宫

3

我尝试使用SpriteKit创建迷宫,我的迷宫打印到控制台上的样子如下:

###########
# #     # #
# ### # # #
#     #   #
######### #
# #     # #
# # # ### #
# # #   # #
# # ### # #
#     #   #
###########

看起来不错,但屏幕上的迷宫看起来像这样:

enter image description here

我的代码如下:

for (int a = 0; a < size * 2 + 1; a++)
{
    for (int b = 0; b < size *2 + 1; b++)
    {
        MazeCell* cell;
        NSNumber* number = [[arrayMaze objectAtIndex:a]objectAtIndex:b];

        if (number.integerValue == 1)
        {
            cell = [[MazeCell alloc]initWithType:1 sort:0];
        }
        else
        {
            cell = [[MazeCell alloc]initWithType:0 sort:1];
        }

        if (number.integerValue == 1)
            printf("#");
        else
            printf(" ");

        cell.position = CGPointMake(startPoint.x+(16*a), startPoint.y+(16*b));
        [self addChild:cell];
    }
    printf("\n");
}

我知道将一个数组打印到屏幕上应该很简单,但是好像我漏掉了什么... 感谢您的帮助 :)
2个回答

2
这样想:每次增加 a 时,您会打印一个换行符。因此,我们可以推断出,a 表示纵坐标,b 表示横坐标,用于打印
另一方面,当您计算单元格的位置时,您正在使用 a 来计算单元格的横坐标,而使用 b 来计算单元格的纵坐标。
基本上,您有两个选择。
  1. You can swap the variable between the for loops:

    for (int b = 0; b < size * 2 + 1; b++) {
        for (int a = 0; a < size * 2 + 1; a ++) {
            ...
    
  2. You can swap the variables when computing the cell coordinates:

    cell.position = CGPointMake(startPoint.x+(16*b), startPoint.y+(16*a));
    
在遍历二维网格时,通常将外部循环视为 y 循环。因此,我的建议是您进行以下更改:
  1. a 重命名为 y
  2. b 重命名为 x
  3. 在计算单元格坐标时交换变量。
因此:
for (int y = 0; y < size * 2 + 1; y++) {
    for (int x = 0; x < size *2 + 1; x++) {
        MazeCell* cell;
        NSNumber* number = arrayMaze[y][x];

        if (number.integerValue == 1) {
            cell = [[MazeCell alloc] initWithType:1 sort:0];
        } else {
            cell = [[MazeCell alloc] initWithType:0 sort:1];
        }

        if (number.integerValue == 1) {
            printf("#");
        } else {
            printf(" ");
        }

        cell.position = CGPointMake(startPoint.x+(16*x), startPoint.y+(16*y));
        [self addChild:cell];
    }
    printf("\n");
}

此外,您的打印输出将原点放置在顶部,并向下增加 y 坐标。然而,SpriteKit 将原点放置在左下角,并向上增加 y 坐标。(请参见 Sprite Kit Programming Guide 中的{{link1:“使用锚点在视图中定位场景坐标系”}}。如果您希望 Y 轴在图形和打印输出中运行相同方向,请将场景的锚点设置为其左上角,并将 yScale 设置为 -1。或者,您可以从父对象的高度中减去每个 y 坐标(如 Horvath 的答案中所示)。

他不仅交换坐标,还旋转迷宫。 - peterh

2
是的,您正在以顺时针90度旋转打印此内容。也许一个解决方案是对这个旋转进行补偿:
cell.position = CGPointMake(startPoint.x+16*b, size*2-startPoint.y+16*(size*2-a));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接