我在 GameScene 类中有这个函数
class GameScene: SKScene {
func runGameOver() {
self.removeAllActions()
self.enumerateChildNodes(withName: "Bullet") {
bullet, stop in
bullet.removeAllActions()
}
self.enumerateChildNodes(withName: "Enemy") {
enemy, stop in
enemy.removeAllActions()
}
}
}
我正在尝试从另一个类中的另一个函数运行 runGameOver 函数。每当敌人离开屏幕并从 livesNumber 中取 1 时,就会调用 loseALife 函数。
如果我为 GameScene 声明了一个变量/常量,如下所示 让 object = GameScene() 然后使用 object.runGameOver() 调用函数应用程序崩溃,因此,我调用它如下所示 GameScene().runGameOver() 但它没有工作。我应该如何访问该功能?
class LivesSystem {
func loseALife() {
livesNumber -= 1
if livesNumber == 0 {
GameScene().runGameOver()
}
}
}
最佳答案
问题是你正在制作一个新的假 GameScene()
,这当然是错误的方法。为了能够与真实(当前呈现的那个)GameScene
交互,您可以使用NotificationCenter
,这样做:
1) 在您的 GameScene 中让我们观察游戏结束:
class GameScene: SKScene {
override func sceneDidLoad() {
super.sceneDidLoad()
NotificationCenter.default.addObserver(forName: Notification.Name.init("game_over"), object: nil, queue: OperationQueue.main) { [weak self] (notification) in
self?.runGameOver()
}
}
func runGameOver() {
self.removeAllActions()
self.enumerateChildNodes(withName: "Bullet") {
bullet, stop in
bullet.removeAllActions()
}
self.enumerateChildNodes(withName: "Enemy") {
enemy, stop in
enemy.removeAllActions()
}
}
}
2) 在您的 LivesSystem
中,只要需要,启动通知:
class LivesSystem {
var livesNumber = 3
func loseALife() {
livesNumber -= 1
if livesNumber == 0 {
NotificationCenter.default.post(name: Notification.Name.init("game_over"), object: nil)
}
}
}
关于swift - 从 SpriteKit 中的另一个类访问 GameScene() 内的函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48739015/