Spritekit:从UIButtons传递到SKSpriteNode

时间:2018-09-26 12:06:38

标签: ios swift sprite-kit

我正在开发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!")
}

}

1 个答案:

答案 0 :(得分:0)

使用SKAction执行此操作。

在touches中开始删除setScale(0.9)和self.alpha = 0.5,请使用:

read

在touchEnded中执行相同操作并添加:

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

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

编辑:

在操场上进行测试:

enter image description here