Is there a way to extract info from the .sks file, e.g. a SKSpriteNode’s position?

30 views Asked by At

Using swift, is there a way to directly extract info from the .sks file, e.g. a SKSpriteNode’s position?

I know the .sks file is a static snapshot and can not be dynamically changed, that is, written to.

In my case, my .sks file shows the initial layout of all my game pieces. 2 are movesble.

I need to extract the initial size and position of these 2 and not hard code these values.

1

There are 1 answers

0
ulr On

Here is some code which I modified from an older udemy course to avoid the use of deprecated init parameters for NSKeyedArchiver. You can use as an extension to SKNode to load a SKS file as SKNode. Here's the snippet. Hope, this helps.

extension SKNode {

  class func unarchiveFromFile (file: String) -> SKNode? {
      if let path = Bundle.main.path(forResource: file, ofType: "sks") {
          let url = URL(filePath: path)
          do {
              let sceneData = try Data(contentsOf: url, options: .mappedIfSafe)
              let archiver = NSKeyedUnarchiver(forReadingFrom: sceneData)
              archiver.requiresSecureCoding = false
              archiver.setClass(self.classForKeyedArchiver(), forClassName: "SKScene")
              let scene = archiver.decodeObject(of: self, forKey: NSKeyedArchiveRootObjectKey)!
              archiver.finishDecoding()
            
              return scene
          }
          catch {
              print(error.localizedDescription)
              return nil
          }
      } else {
          return nil
      }
    
   }
}