Spritekit: passing from UIButtons to buttons as SKSpriteNode

六月ゝ 毕业季﹏ 提交于 2019-12-11 06:55:18

问题


I’m working on a SpriteKit game and at first I put 4 UIButton in my GameplayScene, but then I decided to create individual buttons as SKSpriteNode, programmatically made, and use a class (class Button: SKSpriteNode). I want my buttons fade and scale a little when pressed and then turn back to the original state. Buttons fade and scale down, but they stay in that state, don’t go back to normal state. What’s wrong with my code?

import SpriteKit

protocol ButtonDelegate: NSObjectProtocol { func buttonClicked(sender: Button) }

class Button: 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:


Use SKAction to do this.

In touchesBegan remove setScale(0.9) and self.alpha = 0.5, use :

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

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

in touchEnded do the same and add:

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

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

EDIT:

Here a test into a Playground:



来源:https://stackoverflow.com/questions/52517377/spritekit-passing-from-uibuttons-to-buttons-as-skspritenode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!