Spritekit:从 UIButtons 传递到按钮作为 SKSpriteNode

Spritekit: passing from UIButtons to buttons as SKSpriteNode

我正在开发 SpriteKit 游戏,起初我在我的 GameplayScene 中放置了 4 个 UIButton,但后来我决定创建单独的按钮作为 SKSpriteNode,以编程方式制作,并使用 class (class 按钮:SKSpriteNode)。 我希望我的按钮在按下时褪色并稍微缩放,然后恢复到原始状态。 按钮淡出并缩小,但它们保持该状态,不会回到正常状态。 我的代码有什么问题?

导入 SpriteKit

协议 ButtonDelegate:NSObjectProtocol { func buttonClicked(发件人:按钮) }

class 按钮: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!")
}

}

使用 SKAction 执行此操作。

在 touchesBegan 中删除 setScale(0.9) 和 self.alpha = 0.5,使用 :

        let scaleAction = SKAction.scale(to: 0.5, duration: 1)
        self.run(scaleAction)

        let fadeAction = SKAction.fadeAlpha(to: 0.5, duration: 1)
        self.run(fadeAction)

在 touchEnded 中做同样的事情并添加:

    self.removeAllActions()
    let scaleAction = SKAction.scale(to: 1, duration: 1)
    self.run(scaleAction)

    let fadeAction = SKAction.fadeAlpha(to: 1, duration: 1)
    self.run(fadeAction)

编辑:

这里是 Playground 测试: