Panda Pig • Patty original or translated works. Welcome reprint, Reprint please indicate the source.
If you feel that the writing is not good please more advice, if you feel good please support a lot of praise. Thank you! Hopy;)
In order to facilitate the debugging of physical behavior in Spritekit, we can draw on the powerful mechanism of Xcode's playground. We just need to change our code at any time to see the changes in the physical objects immediately in the observation window.
Now in order to observe a certain delay time for the eyes, we write a delay method:
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() }}
Then extend the Skscene class, adding 2 new instance methods:
extension skscene{func switchwinddirection (timer:NSTimer) { Blowingright =!blowingright WindForce = Cgvector (dx:blowingright?) 50 :-< span class= "Hljs-number" >50 , dy: 0 ) } func Windwithtimer (timer:nstimer) {scene! ( "sand" ) {node,_ In node.physicsbody ! .applyforce (WindForce)} scene! .enumeratechildnodeswithname ( "shape" ) {node,_ in node.physicsbody !.applyforce (WindForce)}}}
We sway the physical objects in the scene over time, simulating the effect of a strong wind.
We also need to find a place to call these two methods, first trying to call in 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 )}
But actually the playground shows that the corresponding method is not called, and then moving the Nstimer call outside of the delay can accomplish the effect.
The reason is simple, the delay call in delay is executed in the main queue, should be placed in the main queue to execute, we re-write a Delayinmain method:
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() }}
Then call the Nstimer timer method in which you can:
Why updates to Spritekit physical objects are not valid in Xcode's playground