我正在开发SpriteKit游戏,起初我在GameplayScene中放置了4个UIButton,但后来我决定以编程方式创建单个按钮,如SKSpriteNode,并使用一个类(Button类:SKSpriteNode)。 我希望按钮按下时淡出并缩放一点,然后再返回到原始状态。 按钮会逐渐消失并按比例缩小,但它们会保持该状态,而不会回到正常状态。 我的代码有什么问题?
导入SpriteKit
协议ButtonDelegate:NSObjectProtocol { func buttonClicked(发送方:按钮) }
类按钮:SKSpriteNode {
weak var delegate: ButtonDelegate!
var buttonTexture = SKTexture()
init(name: String) {
buttonTexture = SKTexture(imageNamed: name)
super.init(texture: buttonTexture, color: .clear, size: buttonTexture.size())
self.isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var touchBeganCallback: (() -> Void)?
var touchEndedCallback: (() -> Void)?
weak var currentTouch: UITouch?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
touchBeganCallback?()
if isUserInteractionEnabled {
setScale(0.9)
self.alpha = 0.5
if let currentTouch = touches.first {
let touchLocation = currentTouch.location(in: self)
for node in self.nodes(at: touchLocation) {
delegate?.buttonClicked(sender: self)
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
setScale(1.0)
self.alpha = 1.0
touchEndedCallback?()
print("tapped!")
}
}