0

我正在尝试编写一个例程来掷骰子。我希望在登陆最终数字之前改变几次脸。下面的代码没有显示换模面。我添加了 sleep 语句,希望它有时间更新,但它只是保留初始面直到结束,然后显示最终面。更改纹理后是否有要添加的语句以强制视图更新?

func rollDice() {
    var x: Int
    for var i = 0; i < 50; i++
    {
        x = GKRandomSource.sharedRandom().nextIntWithUpperBound(6)

        let texture = dice[0].faces[x]
        let action:SKAction = SKAction.setTexture(texture)

        pieces[3].runAction(action)


        pieces[3].texture = dice[0].faces[x]
        NSThread.sleepForTimeInterval(0.1)
        print(x)
    }
}
4

2 回答 2

0

正如评论中所指出的,屏幕仅在主线程上重绘。因此,您可以让掷骰子在后台线程上进行,并在主线程上重绘屏幕:

func rollDice() {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
        for i in 0..<50 {
            let x = GKRandomSource.sharedRandom().nextIntWithUpperBound(6)

            dispatch_async(dispatch_get_main_queue) {
                let texture = dice[0].faces[x]
                let action:SKAction = SKAction.setTexture(texture)

                pieces[3].runAction(action)

                pieces[3].texture = dice[0].faces[x]
                NSThread.sleepForTimeInterval(0.1)
                print(x)
            }
        }
    }
}
于 2016-02-25T22:01:04.343 回答
0

感谢您的帮助。在阅读了一些关于 Timers 的内容后,我想出了以下代码:

func rollDice() {
    rollCount = 0
    timer = NSTimer.scheduledTimerWithTimeInterval(0.05, target:self, selector: "changeDie", userInfo: nil, repeats: true)
}

func changeDie () {
    x = GKRandomSource.sharedRandom().nextIntWithUpperBound(6)
    print(x)
    let texture = dice[0].faces[x]
    let action:SKAction = SKAction.setTexture(texture)
    pieces[3].runAction(action)
    ++rollCount
    if rollCount == 20 {
        timer.invalidate()
    }
}
于 2016-02-27T05:06:28.957 回答