【问题标题】:Spritekit: passing from UIButtons to buttons as SKSpriteNodeSpritekit:从 UIButtons 传递到按钮作为 SKSpriteNode
【发布时间】:2018-09-26 12:06:38
【问题描述】:

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

导入 SpriteKit

protocol 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!")
}

}

【问题讨论】:

    标签: ios swift sprite-kit


    【解决方案1】:

    使用 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 的测试:

    【讨论】:

    • 谢谢,但我也遇到了同样的问题...似乎“touchesEnded”不起作用...
    • 可能是因为回调到 touchBegan
    • @DaniChi 我尝试进入一个游乐场,它就像一个魅力,看看我要添加到答案的视频。当你调用 touchBeganCallback?() 你想发生什么?你在它的身体里做什么?你从回调中返回吗?
    • 你是对的。我创建了另一个项目,它也与我的旧代码完美配合。无论如何,我认为我的 GamePlayScene 存在一些问题......我正在检查代码
    • 感谢您的帮助,我真的很沮丧。我完全重新制作了该应用程序,现在它可以完美运行。还是看不懂哪里错了,代码都是一样的……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    相关资源
    最近更新 更多