【问题标题】:Label's text not fading out标签的文本不会淡出
【发布时间】:2020-10-26 21:25:07
【问题描述】:

我目前正在使用 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 标签将显示“超级跳跃”。然后调用函数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.

感谢您的宝贵时间。

【问题讨论】:

    标签: swift sprite-kit label skaction


    【解决方案1】:

    对于 SpriteKit,您最好使用各种 SKAction 初始化程序,而不是尝试通过 GCD 执行操作。对于您的示例,例如:

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

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

    【讨论】:

    • 非常感谢!我实际上不知道您可以在序列之后将代码放在括号中,但这非常有效!
    • @Frævik 括号中的代码是一个闭包,是run 的第二个参数。 Swift 的尾随闭包语法使得这种习语非常普遍。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2014-08-21
    • 2017-04-04
    相关资源
    最近更新 更多