如何从场景本身外部更新SpriteKit场景。例如。如何通过按UIButton更新SKLabelNode。
场景
class GameScene: SKScene {
var myLabel:SKLabelNode = SKLabelNode()
override func didMoveToView(view: SKView) {
myLabel.text = "Initial State"
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
self.addChild(myLabel)
}
func didPressButton() {
myLabel.text = "Pressed! "
}
的ViewController
import UIKit
import SpriteKit
class GameViewController: UIViewController {
@IBAction func didPressButton(sender: AnyObject) {
if let scene = GameScene(fileNamed:"GameScene") {
scene.didPressButton()
}
}
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
let skView = self.view as! SKView
skView.presentScene(scene)
}
}
…
}
我知道场景中通常的touchesBegan
可以很好地更新场景中的SKLabelNode。但我特别感兴趣的是从外部事件中更新场景。有什么想法吗?
答案 0 :(得分:0)
在你的按钮所在的文件中:
protocol PauseBtnSelectorDelegate {
func didPressPauseBtn(pauseBtn:SKSpriteNode)
}
class HUD: SKNode {
var pauseBtnDelegate:PauseBtnSelectorDelegate?
var pauseBtn :SKSpriteNode!
...
func pauseBtnTap(sender:SKSpriteNode) {
print("pauseBtn touched")
pauseBtnDelegate!.didPressPauseBtn(sender)
}
}
在您要通知点击事件的文件中:
class GameScene: SKScene,PauseBtnSelectorDelegate {
var hud: HUD!
...
override func didMoveToView(view: SKView) {
super.didMoveToView(view)
// Adding HUD
self.hud = HUD(currentScene: self,nodeSize: self.frame.size)
self.hud.pauseBtnDelegate = self
self.addChild(hud)
}
func didPressPauseBtn(pauseBtn:SKSpriteNode) {
print("pauseBtn touched")
// Pause the game
}
}