0

I create my sprite kit games programmatically and the sks files end up just confusing me.

Is there a way to load or create a tile map node without having to use the sks/scene file?

Negora
  • 281
  • 4
  • 13
  • This [post](http://stackoverflow.com/questions/39533705/programmatically-create-sktilemapnode-in-swift/39544119#39544119) discusses how to create the map with an existing tileset created in the editor. – Mark Brownsword Jan 17 '17 at 02:47
  • 1
    This [post](http://stackoverflow.com/questions/41352251/what-is-the-proper-way-to-programmatically-create-a-spritekit-sktilemap/41434435#41434435) discusses how to create both tileset and map. – Mark Brownsword Jan 17 '17 at 02:47
  • I figured out a way to do it, first add this extension: – Negora Jan 17 '17 at 04:24
  • 1
    if you add your solution as an answer, you might get the `Self Learner` badge! – Mark Brownsword Jan 17 '17 at 19:40

1 Answers1

1

I figured out a way to to do it:

  • 1) Create a SKS file called tilemaps
  • 2) Create all your maps in there
  • 3) Add this extension to load that scene file in your current scene:

    extension SKNode {
    class func unarchiveFromFile(file : NSString) -> SKNode? {
        if let path = Bundle.main.path(forResource: file as String, ofType: "sks") {
            let sceneData = NSData(contentsOfFile: path)
    
            let archiver = NSKeyedUnarchiver(forReadingWith: sceneData as! Data)
    
            archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
            let scene = archiver.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as! SKNode
            archiver.finishDecoding()
            return scene
        } else {
            return nil
        }
    }
    

    }

Then grab the tile map from the sks file. Weird trick is that you have to remove it from its parent first:

    guard 
      let tileScene = SKScene.unarchiveFromFile(file: "TileMaps"),
      let testMap = tileScene.childNode(withName: "Dungeon1")
        as? SKTileMapNode else {
            fatalError("Background node not loaded")
    }
    self.testMap = testMap
    self.testMap.removeFromParent()
    self.testMap.zPosition = 1200

    self.addChild(testMap)
Negora
  • 281
  • 4
  • 13