I'm currently making a very simple 2D soccer game using SpriteKit and Swift. In this game, various power-ups can appear, and these disappear and affect the game in different ways if hit by the ball. When such a power-up, for example the "Super jump" is hit, a label is supposed to say "Super jump", wait one second, and then fade out in 0.5 seconds. The way I've done this is as follows (the didInteract
function is called when the power-up and ball collides):
func didInteract_superJump() {
notifications.alpha = 1
notifications.text = "Super jump"
updateNotificationLabel()
// code to actually affect the game goes here ...
}
Now the notifications
label will display "Super jump". The function updateNotificationLabel
is then called:
func updateNotificationLabel() {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
self.notifications.run(SKAction.fadeOut(withDuration: 0.5))
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
self.notifications.text = ""
})
}
}
This might be a bad way of doing it, since it only works sometimes. I really have no clue as for what to do. I've read through my code several times, and it seems like is should work – as mentioned, the text fades away sometimes. Other times, it just sits there and never disappears.
This weird error message may or may not be related, but it appeared in my console: Sokar Hedz[1936:57105] [general] __CFRunLoopModeFindSourceForMachPort returned NULL for mode 'kCFRunLoopDefaultMode' livePort: 6271.
Thank you for your time.
For SpriteKit, you're better off using the various SKAction
initializers than trying to do things via GCD. For your example, something like:
func updateNotificationLabel() {
notifications.run(.sequence([.wait(forDuration: 1.0),
.fadeOut(withDuration: 0.5),
.wait(forDuration: 1.0)])) {
self.notifications.text = ""
}
}
(Beware typos since I haven't tried to compile this, but it should give you the idea.)