标签的文字不会淡出

Label's text not fading out

我目前正在使用 SpriteKit 和 Swift 制作一个非常简单的 2D 足球游戏。在此游戏中,可能会出现各种道具,如果被球击中,这些道具会消失并以不同的方式影响游戏。当这样的能量提升,例如“超级跳跃”被击中时,标签应该写着“超级跳跃”,等待一秒钟,然后在 0.5 秒后淡出。我这样做的方式如下(当启动和球碰撞时调用 didInteract 函数):

func didInteract_superJump() {
    notifications.alpha = 1
    notifications.text = "Super jump"
    updateNotificationLabel()
    // code to actually affect the game goes here ... 
}

现在notifications标签会显示“Super jump”。然后调用函数 updateNotificationLabel

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 = ""
        })
    }
}

这可能是一种糟糕的做法,因为它只在有时 有效。我真的不知道该怎么做。我已经通读了我的代码好几遍,看起来应该可以工作——如前所述,文本有时会消失。其他时候,它只是坐在那里,永远不会消失。

这个奇怪的错误消息可能相关也可能不相关,但它出现在我的控制台中:Sokar Hedz[1936:57105] [general] __CFRunLoopModeFindSourceForMachPort returned NULL for mode 'kCFRunLoopDefaultMode' livePort: 6271 .

感谢您的宝贵时间。

对于 SpriteKit,您最好使用各种 SKAction 初始值设定项,而不是尝试通过 GCD 执行操作。对于您的示例,类似于:

func updateNotificationLabel() {
    notifications.run(.sequence([.wait(forDuration: 1.0),
                                 .fadeOut(withDuration: 0.5),
                                 .wait(forDuration: 1.0)])) {
        self.notifications.text = ""
    }
}

(注意拼写错误,因为我还没有尝试编译它,但它应该会给你想法。)