Swift 图像不';加载时直到结束时才更新
我正在写一个掷骰子的程序。我想在最后一个号码登陆之前,脸要换几次。下面的代码不显示换模面。我添加了sleep语句,希望它能有时间进行更新,但它只会保留最初的人脸直到结束,然后显示最终的人脸。在更改纹理后是否要添加语句以强制更新视图Swift 图像不';加载时直到结束时才更新,swift,gameplay-kit,Swift,Gameplay Kit,我正在写一个掷骰子的程序。我想在最后一个号码登陆之前,脸要换几次。下面的代码不显示换模面。我添加了sleep语句,希望它能有时间进行更新,但它只会保留最初的人脸直到结束,然后显示最终的人脸。在更改纹理后是否要添加语句以强制更新视图 func rollDice() { var x: Int for var i = 0; i < 50; i++ { x = GKRandomSource.sharedRandom().nextIntWithUpperBou
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)
}
}
func rollDice(){
变量x:Int
对于var i=0;i<50;i++
{
x=GKTrandomSource.SharedAndom().NextInWithUpperbound(6)
让纹理=骰子[0]。面[x]
let action:SKAction=SKAction.setTexture(纹理)
件[3]。运行操作(操作)
碎片[3]。纹理=骰子[0]。面[x]
NSThread.sleepForTimeInterval(0.1)
打印(x)
}
}
正如评论中所指出的,屏幕仅在主线程上重画。因此,您可以让掷骰子在背景线程上进行,并在主线程上重新绘制屏幕:
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)
}
}
}
}
func rollDice(){
调度异步(调度获取全局队列(调度队列优先级后台,0)){
对于0中的i..谢谢您的帮助。在阅读了一些关于计时器的内容后,我想到了以下代码:
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()
}
}
直到函数退出后,屏幕才会显示。你需要设置你的模具面,然后设置一个计时器,以便稍后更新下一个面,并允许函数退出。如果不这样做,模具将始终显示你设置的最后一个面。你为什么要将当前线程置于睡眠状态?我猜这是主线程?应用程序应该响应e尽可能多(根据文档)。是否使用SpriteKit?如果是,请使用SKAction或update:method及其传递的currentTime参数来执行与时间相关的操作。