Deepak
Deepak

Reputation: 6812

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)

Upvotes: 3

Views: 1900

Answers (2)

B.T.
B.T.

Reputation: 610

A more recent article addressed an approach to this, illustrating an approach to map a GKPerlinNoiseSource to an SKTileMapNode. I think this is probably more useful than the accepted answer (though the accepted answer pre-dates this article by several years).

https://www.hackingwithswift.com/example-code/games/how-to-create-a-random-terrain-tile-map-using-sktilemapnode-and-gkperlinnoisesource

Please note this article is in Swift 5.2.

Upvotes: 0

Whirlwind
Whirlwind

Reputation: 91

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.

Upvotes: 4

Related Questions