Search code examples
iosswiftsprite-kitprocedural-generationgameplay-kit

Procedural Map Generation - SpriteKit and GameplayKit


I have the following code to generate noise using the new GameplayKit's GKNoise. I am not sure how I can use that with the SKTileMapNode. Has anyone tried this ? At the moment the noise is applied to each tile but not to the overall TileMap. Is there a way to use the generated noise to the whole map ?

let noise: GKNoise = GKNoise(noiseSource: GKPerlinNoiseSource())
let noiseMap: GKNoiseMap = GKNoiseMap(noise: noise)
let texture: SKTexture = SKTexture(noiseMap: noiseMap)

let tileDef = SKTileDefinition(texture: texture)
let tileGroup = SKTileGroup(tileDefinition: tileDef)
let tileSet = SKTileSet(tileGroups: [tileGroup])

// Create a tile map
let tileSize = CGSize(width: 32.0, height: 32.0)
let tileMap = SKTileMapNode(tileSet: tileSet, columns: 16, rows: 16, tileSize: tileSize)

// Fill the entire map with a tile group
tileMap.fill(with: tileGroup)

self.addChild(tileMap)

Solution

  • GKNoise returns noise in the range [-1.0,1.0].

    You need to map this in some meaningful way into you game. A trivial example would be to say that everything between [-1.0,0.0] is water, and everything between (0.0,1.0] is land.

    Once you have decided what this mapping is, just use getValue() on GKNoiseMap to sample once for each tile you want to fill and then use your rule to decide which tile to use.