Reputation: 311
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!")
}
}
Upvotes: 1
Views: 153
Reputation: 908
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:
Upvotes: 0