2016-06-11 28 views
0

在我的xcode項目中,我試圖從一個SKScene轉換到另一個。觸發轉換的是觸摸SKLabelNode。所有這些工作都正常。但是在場景改變後,我的班級中沒有任何控制「StartScence.sks」的代碼可以工作。看起來好像我的「StartScene.swift」和我的「StartScene.sks」沒有鏈接。SKScene和Swift文件不鏈接

這是我GameScene代碼,

import SpriteKit 

class GameScene: SKScene { 

var isTouched: Bool = false 
var booleanTouched: Bool! 
let ns = SKScene(fileNamed: "StartScene") 
let crosswf = SKTransition.crossFadeWithDuration(2) 


override func didMoveToView(view: SKView) { 


    let backgroundimage = SKSpriteNode(imageNamed: "ipbg") 
    backgroundimage.size = CGSize(width: self.frame.size.width, height: self.frame.size.height) 
    backgroundimage.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2) 
    addChild(backgroundimage) 

    let playButton = SKLabelNode(fontNamed: "") 
    playButton.name = "play" 
    playButton.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2 + 100) 
    playButton.text = "Play" 

    let wait = SKAction.waitForDuration(2) 
    let run = SKAction.runBlock({ 


     let randomNumber = Int(arc4random_uniform(UInt32(4))) 

     switch(randomNumber){ 

     case (0): 

      playButton.fontColor = UIColor.blueColor() 

     case 1: 

      playButton.fontColor = UIColor.yellowColor() 

     case 2: 

      playButton.fontColor = UIColor.purpleColor() 

     case 3: 

      playButton.fontColor = UIColor.orangeColor() 

     default: print("default") 


     } 

    }) 

    addChild(playButton) 
    var repeatActionForever = SKAction.repeatActionForever(SKAction.sequence([wait, run])) 
    runAction(repeatActionForever) 
    backgroundimage.zPosition = 1 
    playButton.zPosition = 2 



} 

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 

    let touch = touches.first! as UITouch 
    let touchLocation = touch.locationInNode(self) 
    let touchedNode = nodeAtPoint(touchLocation) 


    if (touchedNode.name == "play"){ 

     scene!.view?.presentScene(ns!, transition: crosswf) 

    }else{ 


    } 


} 

override func update(currentTime: CFTimeInterval) { 
    /* Called before each frame is rendered */ 
} 

}

這是我的 「StartScene.swift」 原位缺口控制 「StartScene.sks」 正確的代碼。

import SpriteKit 

class StartScene: SKScene { 


override func didMoveToView(view: SKView) { 


    print("Scene Loaded") 

} 

} 

回答

2

有兩件事要注意。

  1. 在你的代碼正在加載您.SKS文件中像這樣

    let ns = SKScene(fileNamed: "StartScene") 
    

你的新場景將加載,因爲所有SKS文件是類SKScene的。 但是,它只會使用該類的代碼。

如果你想要它加載你的類中的代碼StartScene,SKScene的一個子類。該行更改爲這個

let ns = StartScene(fileNamed: "StartScene") 
  • 我們還可以使SKS文件中有一個自定義類,而不是它的默認SKScene。所以當它被加載時,它使用一個自定義類。
  • 在Xcode中打開SKS文件,以便您可以給場景一個自定義類。在場景編輯器中,沒有任何選擇。點擊公用程序區域,切換到右側最後一個選項卡的Custom Class Inspector。

    給它一個自定義類的StartScene。

    它應該工作。