Swift: Simple SpriteKit Experimentation


It takes just a few lines of code to build a SpriteKit test bed in playgrounds. Here are some tips to get you started.

1. Build in OS X. OS X playgrounds offer native SpriteKit/Open GL rendering. They do not require you to use the simulator to emulate graphics. Your response time is better, the rendering more fluid, and the code is already designed for cross-platform deployment.

2. Import the XCPlayground module. You use XCPShowView() to render SKScenes. XCPlayground also offers access to continued execution if you add any SKActions.

3. Build and present a scene. Don’t forget to open the assistant editor to view the scene.

// Build scene and view
let sceneSize = CGSizeMake(400.0, 300.0)
let view = SKView(frame: CGRect(origin: CGPointZero, size: sceneSize))
var scene = SKScene(size: sceneSize)
XCPShowView("Scene", view); view.presentScene(scene)

4. Go. You’re ready to implement and test basic SpriteKit functionality.


I built the following example the other night to help a colleague who was confused by the role of zPosition properties in child nodes. By throwing together a few shape nodes, it took almost no effort to demonstrate how the relative zPositions could cause a child node to pop on top of another node with a different z ordering.

You can ignore all those little red error messages. They have nothing to do with the code (I think they’re QuickLook preview errors within the playground) and they won’t affect the SpriteKit execution.

Playgrounds allow you to import routines into secondary sources, so you can really simplify and focus your testing on just those elements you need to explore. If there’s something that works, and you don’t need to be looking at it or adjusting it, toss it into another file in the Sources group in the Project Navigator.

The next video shows how you can interactively adjust SKAction parameters until you find, for example, the right balance of speed. Notice how incredibly tiny the playground code is. Unlike the first video that shows the entire (but still small) playground code base, there’s another 70 lines of code that create the tiling that I tossed into a secondary file for this example.

By moving those rendering functions away, the playground tidies up to the bare essentials. You could clean it up even further by shunting the some of the view set-up into a secondary file. What you’re left with enables you to work in a simple interactive test environment.

Like the hacks? Read the book.

One Comment

  • Nice tutorial, been searching for something like this in a minute and found this. thanks