How to run different code for different scenes in Xcode sprite-kit?

I create a game in the Xcode 8 sprite set, and I have different levels, but when I load the next level scene, the code for the first level still works. All levels have their own fast files with the same names as their respective scenes. How to run code designed for different scenes?

this is a function that changes levels

class func level(_ levelNumber: Int) -> GameScene?
{
    guard let scene = GameScene(fileNamed: "Level_\(levelNumber)") else
    {
        return nil
    }

    scene.scaleMode = .aspectFit
    return scene
}

this is the code i call to change the levels:

guard let scene = GameScene.level(currentScene) else
{
    print("Level \(self.currentLevel+1) is missing?")
    return
 }

 scene.scaleMode = .aspectFit
 view.presentScene(scene)
+4
source share
1 answer

Personally, I handle it a little differently.

I like to make my level files in the scene editor, this makes them very fast.

GameScene.swift GameScene.sks(, gameHUD, , , ... --)

Level1.sks, Level2.sks .. Level, , Level.sks.

GameScene , .

. , , sks Levels GameScene, GameScene .

func createLevel(levelID: Int) {

    if let levelNode = SKReferenceNode(fileNamed: "Level\(levelID)") {

        if let background = levelNode.childNode(withName: "backgroundTiles") as? SKTileMapNode {
            background.move(toParent: self)
        }

        if let water = levelNode.childNode(withName: "waterTiles") as? SKTileMapNode {
            water.move(toParent: self)
        }

        if let badGuy = levelNode.childNode(withName: "badGuy") as? SKSpriteNode {
            self.badGuy = badGuy
            badGuy.move(toParent: self)
        }
    }
}
+2

Source: https://habr.com/ru/post/1682511/


All Articles