在这里面,我没有看到 goesTo 被分配给 nextScene。我认为这是一个范围问题,但还不足以解决它:
//
import SpriteKit
class MenuButton: SKLabelNode {
var goesTo: SKScene?
override init() {
super.init()
print("test... did this get called? WTF? HOW/WHY/WHERE?")
}
convenience init(text: String, color: SKColor, destination: SKScene){
self.init()
self.text = text
self.fontColor = color
goesTo = destination
self.isUserInteractionEnabled = true
print("gooing tooooo....", text, goesTo!) // WORKS!!!
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let nextScene = goesTo {
self.scene?.view?.presentScene(nextScene, transition: SKTransition.doorsOpenVertical(withDuration: 0.25))
print("going to", nextScene) // This is NIL! SO NEVER GETS CALLED!
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
最佳答案
你的代码是正确的,你可以简单地测试它,例如:
GameScene.swift
import SpriteKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
print("- \(type(of:self))")
let helloScene = HelloScene.init()
helloScene.name = "helloScene"
let button1 = MenuButton.init(text: "HELLO", color: .red, destination: helloScene)
addChild(button1)
button1.position = CGPoint(x:self.frame.midX,y:self.frame.midY)
}
}
您会在屏幕中间看到一个红色标签,上面写着“HELLO”。
如您所见,您的打印品对于您的两种方法来说看起来都不错。
HelloScene.swift
import Foundation
import SpriteKit
class HelloScene: SKScene {
override func didMove(to view: SKView) {
print("- \(type(of:self))")
self.backgroundColor = .blue
}
}
调试控制台:
关于swift - 从类根到 init 内部,再到 touchesBegan 内部的作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40517013/