Search code examples
iossprite-kitsktilemapnode

Generating random terrain in SpriteKit


First of all I want to mention that I have no deep knowledge about games or SpriteKit framework (however, I have good programming skills).

I want to create a 2D game for iPhone and iPads. So far, I know that I have to use SpriteKit. However, the most import of this game is the terrain. I should be able to generate it dynamically so it will have curves (but not spike edges) like the black line from the attached image. Also, I would like to have the down part of ground in two separate layers (one thin layer of green to simulate grass and the rest some brownish color to simulate dirt), but this is something nice to have.

Also I would like to know how can I "explode" a little portion of ground when something (like an cannon ball) touches it.

Can someone explain or guide me on how can I achieve this?

example of random generated ground

Thank you!


Solution

  • Map Generation

    There are two approaches that you can try here:

    1. The SKTileMapNode class in SpriteKit
    2. The CGPath class(es) in CoreGraphics.

    The SpriteKit Approach

    Start by taking a look at SpriteKit's tile map features. There's a class called SKTileMapNode that can help you make a tile-based side or top-down view of your game world.

    Apple introduced this at WWDC 2016, and the session video is a good starting point for that. Xcode has a good editor for setting up your tile maps, including variations on specific tiles (called "Tile Variants") and adding metadata to your tiles. All of that is going to be helpful here.

    You can define pre-built groups of tiles as SKTileGroups, for things like two sides of a hill that only make sense next to each other. It might be simple enough to do that and then generate some random combinations. You could then use different variants to show "exploded" tiles.

    The preferred method to create tile groups is to use the editor tools in Xcode. However, should you wish to work with SpriteKit’s tile support programmatically, the following examples discuss the necessary steps.

    -- Apple Documentation, SKTileGroup

    Accordingly, you can use SKTileGroupRule can help you define rules about where to put tiles relative to each other programmatically.

    Here's a tutorial from Ray Wenderlich that takes you through the basics of a tile-based game. Here's another RayWenderlich.com tutorial that discusses procedural level generation.

    The CGPath Approach

    This answer discusses a similar situation where someone asked about drawing curves for use with SpriteKit. It shows some code for generating randomized bezier curves, and links to a second answer with an in-depth discussion of CoreGraphics' handling of adding paths to bezier curves.

    Explosions

    For exploding a tile, have a look at SKEmitterNode. Xcode includes an emitter editor, and you can do some cool stuff with it.