Reputation: 41
I'm building a game in Xcode 8 sprite-kit and I have different levels, but when I load the next level scene, the code for the first level still runs. All of the levels have their own swift files with the same names as their respective scenes. How do I run the code meant for different scenes?
this is the 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 code I call to change levels:
guard let scene = GameScene.level(currentScene) else
{
print("Level \(self.currentLevel+1) is missing?")
return
}
scene.scaleMode = .aspectFit
view.presentScene(scene)
Upvotes: 4
Views: 408
Reputation: 6061
Personally, I handle this a little bit differently.
I like making my level files in the Scene Editor, it makes laying them out very fast.
I put all the core game engine stuff in my GameScene.swift and GameScene.sks files (ie. gameHUD, player, scoring, pause...blah blah blah)
I then create my level files separately as Level1.sks, Level2.sks etc. But these will be of class type Level, and this way you don't have to keep repeating generic stuff that is common on all levels in each Level.sks file.
I then load the GameScene file and handle any objects that are generic to all levels.
Then I load up my Level. It is important to note that when doing it like this and having separate sks files for Levels and GameScene you have to move the objects from the Level file to your GameScene when loading them.
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)
}
}
}
Upvotes: 2