2016-02-25 38 views
0

我正在尝试编写一个例程来掷骰子。在登陆最终号码之前,我想让脸部改变几次。下面的代码不会显示换模的面孔。我添加了睡眠声明,希望它能给它更新的时间,但它只是保持初始状态直到结束,然后显示最后一张脸。在更改纹理以强制更新视图后是否添加语句?加载图像时不更新直到结束

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) 
    } 
} 
+0

直到函数退出后的某个时候,屏幕才会绘制。您需要设置模具面,然后设置一个计时器以便稍后更新下一个面并允许该功能退出。如果不这样做,死亡总是会显示你设定的最后一张脸。 – BergQuester

+0

为什么你把当前的线程睡觉?我想这是主线程?应用程序应该尽可能地进行响应(按照文档)。你在使用SpriteKit吗?如果是这样,请使用SKAction或update:方法及其传递的与时间相关的action的curentTime参数。 – Whirlwind

回答

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) 
      } 
     } 
    } 
} 
0

谢谢你的帮助。在阅读了一些关于定时器的内容之后,我想出了以下代码:

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() 
    } 
} 
相关问题