Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SceneKit Update Method for Physics Simulation

I have played with sprite kit and have used the update method to set things to process each time step. I'm trying to learn some swift with scene kit and can't seem to find the equivalent.

Can you point me to an example of implementing an update method for SceneKit? Thanks.

like image 442
Cherr Skees Avatar asked Jun 27 '14 18:06

Cherr Skees


1 Answers

(Yes, I know this question is about SceneKit, not SpriteKit, but it touches on the commonalities and differences between the two frameworks, so I'll address those in this answer.)

In SpriteKit, the game-loop methods (update, didSimulatePhysics, etc) were originally part of the scene class SKScene. This isn't always the best idea, though — you might want to treat a scene instance more like data than like a place to implement game logic (especially now that scenes can be built completely in the Xcode 6 graphical scene editor). So in iOS 8 and OS X Yosemite, those methods are in two places. If you're already subclassing SKScene for per-frame game logic, you can keep doing that. But if you'd rather put that code elsewhere, you can set a delegate on your scene, and implement the equivalent SKSceneDelegate methods there.

SceneKit has more of a separation of concerns. An SCNScene is much closer to being a pure data-model object, and all rendering-loop functionality managed by the view (or other object) responsible for displaying the scene. Typically you display a scene in an SCNView — but there are other classes that can render scenes, too, so their common API is found in the SCNSceneRenderer protocol. Use the delegate property defined by that protocol to set a delegate for your view, and in your delegate you can implement SCNSceneRendererDelegate methods to participate in key phases of the render loop.

The SceneKit loop phases correspond almost directly to those in SpriteKit: update: becomes renderer:updateAtTime:, didEvaluateActions: becomes renderer:didApplyAnimationsAtTime: (because it includes CoreAnimation-style animations as well as SpriteKit-style actions), etc.


So, for the SceneKit equivalent of the SpriteKit per-frame update method, do this:

  1. Set one of your custom objects (say, a view controller) as the delegate of your SCNView instance.

  2. In that custom class, implement the following method:

    func renderer(_ aRenderer: SCNSceneRenderer!, updateAtTime time: NSTimeInterval) {
        // per-frame code here
    }
    

Or do similar for the other SCNSceneRendererDelegate methods if your per-frame logic needs to happen after actions or physics have been processed.

like image 174
rickster Avatar answered Nov 15 '22 19:11

rickster