【问题标题】:2D Terraria-style terrain generation in Cocos2dCocos2d 中的 2D 泰拉瑞亚风格地形生成
【发布时间】:2011-11-06 13:30:29
【问题描述】:

我一直在困惑这个问题。基本上,正如标题所说,我试图生成一个基于图块的二维地形,如Terraria。到目前为止,我基本上只是生成一堆随机点,这些点最终将成为地形的顶层,如下所示:

- (void)generatePoints
{
    float x = 0;
    float y = 0;
    self.topTerrainPoints = [[CCArray alloc] initWithCapacity:terrainKeyPoints];
    for (int i = 0; i < terrainKeyPoints; i++) {
        _terrainPoints[i] = CGPointMake(x, y);
        if (i != 0) {
            int newElevation = [self getRandomElevation];
            x += 64;
            y += newElevation;
            CCLOG(@"Point added!");
        }
    }
    [self populatePointsWithBlocks];
}

之后,我用“块”(CCSprite 的子类)填充这些点

- (void)populatePointsWithBlocks
{
    for (int i = 0; i < terrainKeyPoints; i++) {
        Block *tile = [[Block alloc] initWithType:kBlockTypeGrass];
        tile.position = ccp(_terrainPoints[i].x, _terrainPoints[i].y);
        [self addChild:tile];
        [self.topTerrainPoints addObject:tile];
        CCLOG(@"Tile added!");
    }
    [self fillInGround];
}

然后我继续在每个块下面填充大约十层:

- (void)fillInGround
{
    for (int j = 1; j < terrainMaxDepth; j++) {
        for (int i = 0; i < terrainKeyPoints; i++) {
            CGPoint newPoint = CGPointMake(_terrainPoints[i].x, _terrainPoints[i].y - 64 * j);
            Block *dirt = [[Block alloc] initWithType:kBlockTypeDirt];
            dirt.position = newPoint;
            [self addChild:dirt];
        }
    }
}

这会产生不错的结果,但如果你明白我的意思,我希望最终在地下也有洞穴和其他材料。

我有两个问题:

  1. 这是生成地形的明智方法吗?如果没有,我应该怎么做?
  2. 如果这种创建地形的方式很好,我将如何将洞穴和不同的方块类型添加到已经生成的地形中。

我希望这一切都有意义,我可以发布图片或回答您可能有的任何问题。

无论如何,谢谢!

编辑:有人吗?

【问题讨论】:

  • 进一步研究的起点:en.wikipedia.org/wiki/Voronoi_diagram
  • 这很有趣,我一定会读一遍,谢谢。
  • 您确定需要生成地形吗?也许它不适合您的游戏,但您始终可以使用 LevelHelper 之类的工具预先创建关卡。您可以创建不同类型的块并对其进行编码,然后只需拖放即可创建您的关卡。 levelhelper.org
  • 感谢您的建议,但是是的,我确实想要随机生成关卡。我希望能创造出像 Terraria 或 Minecraft 这样的游戏。

标签: iphone cocos2d-iphone terrain


【解决方案1】:

我做过类似的事情。你需要做的是一个网格,这样你就可以拥有一个平铺地图。因此您将能够访问块 1、4(但它的像素位置会有所不同。

为此,您应该有一个二维数组。要在 Objective C 中执行此操作,您将需要一个包含其他 NSArray 的 NSArray。第一个数组,将是第二个数组对象的 Y 位置。 例如: [[blockArray objectAtIndex:2] objectAtIndex:5] 将在坐标 (2, 5) 处获得块。

然后您可以创建将网格坐标转换为 cocos2D 像素坐标的方法,反之亦然。

使用此网格的主要原因是您需要随时访问某些块(例如将像素位置转换为我们网格中的位置),而不是求助于所有数组(女巫将使您的游戏延迟很多)并检查块是否碰撞。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 2020-08-03
    • 1970-01-01
    相关资源
    最近更新 更多