Creating a SpriteKit scene

SpriteKit games use a special type of view to render its contents. This special view is always an instance or subclass of SKView. If you want to use SpriteKit with ARKit, you should use ARSKView instead because that view implements some special AR-related behavior, such as rendering the camera feed.

The view itself usually doesn't do much work regarding managing the games or its child views. Instead, the SKScene that contains the view is responsible for doing this work. This is similar to how you usually work with view controllers in other apps.

When you have created a scene, you can tell an SKView to present the scene. From this moment on, your game is running. In the sample code for the game project you created earlier, the following lines take care of loading and presenting the scene:

if let scene = SKScene(fileNamed: "GameScene") {
    scene.scaleMode = .aspectFill
    view.presentScene(scene)
}

When you create your scenes, you can choose whether you want to use .sks files or create scenes programmatically.

When you open the GameScene.swift file that Xcode created for you, most of the code should be pretty self-explanatory. When the scene is added to a view, a couple of SKNode instances are created and configured. The most interesting lines of code in this file are the following:

spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5), SKAction.fadeOut(withDuration: 0.5), SKAction.removeFromParent()]))

These lines set up an animation sequence for the spinning squares that get added when you tap the screen. In SpriteKit, actions are the preferred way to set up animations. You can group, chain, and combine actions to achieve pretty complicated effects. This is one of the many powerful tools that SpriteKit has to offer.

If you examine the code a little bit more, you'll find that copies of spinnyNode are created every time the user taps on the screen, moves their finger, or lifts their finger. Each interaction produces a slightly different copy of spinnyNode so you can determine why spinnyNode was added to the scene by looking at its appearance.

Study this code, play around with it, and try to make sure that you grasp what it does. You don't have to become a SpriteKit expert by any means. Let's have a look at how SceneKit works to prepare to implement your Augmented Reality gallery.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.154.151