code:Explained Adventure

Keeping Up to Date

Sprite Kit games are different from traditional iOS or OS X apps in that everything you see onscreen is being continually redrawn many times a second. From the developer’s perspective, the work of updating and displaying a scene’s nodes, such as sprites or particle emitters, is mostly carried out automatically by Sprite Kit. When you’ve added a sprite into the scene, it continues to be redrawn until you remove it. Similarly, particle emitters continue to emit particles until you explicitly pause them or remove them from the scene.

To turn a static scene into something more interesting, you create and run actions on sprites. The physics simulation takes care of interactions (such as collisions) between physics bodies, and prevents sprites from overlapping. For each frame, Sprite Kit automatically updates each node’s position for changes triggered by actions or after applying the results of the physics simulation.

In Adventure, we also make programmatic adjustments to the nodes in a scene. For example, we move the hero in response to user input, and we move the camera such that the character is always visible. Whenever we move the camera, we must also adjust the layer offsets of parallax sprites. All of this programmatic update logic occurs as part of Sprite Kit’s update loop.

The Update Loop

For each frame, Sprite Kit runs through an update loop that has six key phases, as shown in Figure 4-1.

Figure 4-1 The update loop

Within these phases, there are three opportunities to make programmatic adjustments before Sprite Kit renders the frame:

The start of the loop is the update: method, which is called on the scene before evaluating any actions or simulating physics.

The didEvaluateActions method is called on the scene after Sprite Kit has evaluated any outstanding actions on nodes but before looking at implications from the physics simulation.

The didSimulatePhysics method is called on the scene after Sprite Kit has made any adjustments from the physics simulation. This is the last overridable method call before the view renders the scene and the loop continues again.

In Adventure, we tie into this loop in two places:

We implement update: in APAMultiplayerLayeredCharacterScene to move the hero based on user input. The update: method in turn calls updateWithTimeSinceLastUpdate:, which is implemented by APAAdventureScene to update the individual characters in the scene, as well as the artificial intelligence of all the enemies.

We implement didSimulatePhysics in APAMultiplayerLayeredCharacterScene to move the camera, if necessary, based on the hero position. The APAAdventureScene class overrides this method to hide or show particle emitters based on hero position, then it updates the relative positions of the different image layers that make up parallax trees and caves.

We could have dealt with camera movement, particle emitters, and parallax updates during the initial update: phase, but each of these tasks is tied to the position of the hero. During the update: stage, a Sprite Kit node isn’t necessarily at its final position for the current frame—it could move because of actions, or because of side effects from the physics simulation. For example, if the hero was involved in a collision with another character or a wall, the hero position would change between update: and final rendering.

By delaying position-dependent work until didSimulatePhysics, we guarantee that the hero position is final for the current frame.

Moving the Camera

The Adventure scene is very large—the full background is 4096 x 4096—so only a small portion of the scene is visible at any time. The term camera relates to the concept of the visible area of the scene; there’s no explicit Sprite Kit camera object involved, but you’ll often encounter references to “moving the camera.”

In Adventure all world-related nodes, including background tiles, characters, and foliage, are children of a world node, which in turn is a child of the scene. We change the position of this top-of-tree world node within the scene to give the effect of moving a camera across the level. By contrast, the nodes that make up the HUD are children of a separate node that is a direct child of the scene rather than of the world node, so that the elements in the HUD don’t move when we “move the camera.”

We could have chosen to adjust the world node position so that the hero always appears to be at the center of the visible portion of the scene, which would mean moving the camera whenever the hero moved. Instead, we decided to define a rectangular area in which the hero could move, and to move the camera only if the hero strayed outside those bounds, as shown in Figure 4-2.

Figure 4-2 Camera edge insets

We use the didSimulatePhysics method in APAMultiplayerLayeredCharacterScene to change the position of the world node only if the hero is within kMinHeroToEdgeDistance (256) points of the edge of the current visible area.

If there are multiple players, the camera always follows the default player’s hero.

18

Using performSelector:withObject:afterDelay: with the special delay value of 0.0 means that the selector call occurs after the current pass through the run loop. Using this value ensures that the subclass implementation of didSimulatePhysics will occur before the worldMovedForUpdate property is reset to NO.

We set the worldMovedForUpdate property to YES whenever the camera is moved. The APAAdventure implementation of didSimulatePhysics checks worldMovedForUpdate to determine whether we need to update parallax sprites, or remove any particle emitters that are no longer visible.

Creating the Parallax Effect

Adventure is created from two-dimensional graphical elements. To give the illusion of a three-dimensional world, we built some of the sprites (trees and goblin caves) from multiple image layers; when the camera moves to follow the hero, we adjust the positions of these layers at different rates to simulate depth using a technique known as parallax scrolling.

To understand parallax using a realworld example, imagine that you are a passenger in a moving car, looking through the windows at the buildings and trees alongside the road. As the car moves, the trees closest to you appear to travel through your field of vision much faster than do buildings in the far distance, as shown in Figure 4-3.

Figure 4-3 Real-world parallax

We mimic this effect in Adventure by moving the top layers of a tree or goblin cave a greater distance relative to the center of the camera than the lower layers. Parallax support is provided by the APAParallaxSprite class, from which all characters and trees inherit. Most of the character subclasses set the usesParallaxEffect to NO, but the APATree and APACave classes both set the property to YES.

Whenever we initialize a sprite for parallax, we use the designated initializer for APAParallaxSprite, initWithSprites:usingOffset:, which takes an array of sprite nodes and adds them as children of the container sprite at decreasing z-positions.

We initialize the goblin caves using the APACave designated initializer, initAtPosition:, which initializes the cave in the same way, using child sprites with the cave_base and cave_top textures.

Each time we add a parallax sprite to the world in APAAdventureScene, we add it to an array of parallaxSprites.

Updating Parallax Offsets

We update the offsets of parallax sprites each time through the update loop. Because the offset changes based on the camera position, and because the camera position depends on the hero position, the APAAdventureScene class updates parallax offsets in didSimulatePhysics, after the APAMultiplayerLayeredCharacterScene class implementation of the method has adjusted the world position.

Adventure: APAAdventureScene.m -didSimulatePhysics

- (void)didSimulatePhysics {

[super didSimulatePhysics];

... (Get the position of the default hero, or hero spawn point)

if (!self.worldMovedForUpdate) {

return;

}

...

for (APAParallaxSprite *sprite in self.parallaxSprites) {

if (APADistanceBetweenPoints(sprite.position, position) >= 1024) {

continue;

}

[sprite updateOffset];

}

}

5

We need to update offsets only if the world node has moved.

10

We need to update only the offsets of sprites that are currently visible, or soon to be visible. Therefore we check the distance between the sprite and the hero; if no hero is visible, we use the hero spawn point—the starting point in the level.

The updateOffset method is implemented by the APAParallaxSprite class to adjust the offsets of each child sprite node relative to the center of the screen.

We bias the offset directions to the (–1.0, 1.0) range relative to the center of the screen.

14

Each child node is offset by an increasing amount; the top child is therefore offset the most.

Keeping the Game Running Smoothly

To keep everything looking smooth to the user, the optimal redraw rate is 60 frames per second. This means that the entire update loop for each frame must take less than 16.7 milliseconds. In addition to optimizing the code that we wrote for update: and didSimulatePhysics, we adopted various strategies to try to minimize the amount of time it takes Sprite Kit to update everything in the scene.

Emitters are one of the most performance-intensive aspects of a Sprite Kit game, so we used the Xcode particle emitter editor to minimize the number of particles onscreen at any time while still achieving the desired effect. Each time through the update loop, we also pause any emitters that aren’t visible:

Much of the work in didSimulatePhysics needs to be done only if the camera moved, so we check the worldMovedForUpdate property (set by APAMultiplayerLayeredCharacterScene) and return early if the world node didn’t move.