Xcode的playground中對於SpriteKit物理對象的更新為何無效

來源:互聯網
上載者:User

標籤:

大熊貓豬·侯佩原創或翻譯作品.歡迎轉載,轉載請註明出處.
如果覺得寫的不好請多提意見,如果覺得不錯請多多支援點贊.謝謝! hopy ;)

為了便於SpriteKit中物理行為的調試,我們可以藉助於Xcode的playground的強大機制.我們只需要隨時修改我們的代碼,就可以在觀察窗中立即觀察到物理對象的變化.

現在為了給眼睛觀察一定延時時間,我們寫一個延時方法:

public func delay(seconds seconds:Double,completion:()->()){    let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * seconds))    dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)){        completion()    }}

然後擴充SKScene類,添加2個新的執行個體方法:

extension SKScene{    func switchWindDirection(timer:NSTimer){        blowingRight = !blowingRight        windForce = CGVector(dx: blowingRight ? 50:-50, dy: 0)    }    func windWithTimer(timer:NSTimer){        scene!.enumerateChildNodesWithName("sand"){node,_ in            node.physicsBody!.applyForce(windForce)        }        scene!.enumerateChildNodesWithName("shape"){node,_ in            node.physicsBody!.applyForce(windForce)        }    }}

我們隨著時間左右搖擺情境中的物理對象,類比大風吹過的效果.

我們還需要找地方調用這兩個方法,首先嘗試在delay中調用:

delay(seconds: 2.0){    NSTimer.scheduledTimerWithTimeInterval(0.05, target: scene, selector: #selector(SKScene.windWithTimer(_:)), userInfo: nil, repeats: true)    NSTimer.scheduledTimerWithTimeInterval(3.0, target: scene, selector: #selector(SKScene.switchWindDirection(_:)), userInfo: nil, repeats: true)    scene.physicsWorld.gravity = CGVector(dx: 0, dy: -9.8)}

但是實際上playground中顯示並沒有調用其中對應的方法,後將NSTimer的調用移到delay之外調用卻可以完成效果,這是為何?

原因很簡單,delay中的延時調用是在主隊列中執行的,應該放在main隊列中執行,我們重新寫一個delayInMain方法:

public func delayInMain(seconds seconds:Double,completion:()->()){    let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * seconds))    dispatch_after(popTime, dispatch_get_main_queue()){        completion()    }}

然後在其中調用NSTimer的定時器方法就可以了:

Xcode的playground中對於SpriteKit物理對象的更新為何無效

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.