Categories
Uncategorized

Writing iOS games with Swift and Sprite Kit, part 1: The power of actions

get your game onI’m the co-organizer of the Tampa iOS meetup, a monthly gathering of iOS developers based in the Tampa Bay area, and we recently had a session on game development with Sprite Kit that garnered a fair bit of attention. This series of articles takes some of the ideas from that session and uses them as a jumping-off point for exploring game development techniques using Apple’s Sprite Kit framework.

In this first article in the series, we’ll cover enough Sprite Kit to create an app that displays the animated scene below. Best of all, we’ll do it in 26 lines of code:

If you’re comfortable with building basic iOS apps, you shouldn’t have any problem following along.

Setting up the project

Create a new Game project in Xcode by selecting File → New → Project… In the “Choose a template for your new project” window that appears:

  • Select Application under iOS from the list on the left-hand side, and
  • select Game from icon list of template types on the right-hand side

new project

In the “Choose options for your new project” window, give your app a name in the Product Name: text field (I named mine “SpriteKitActions01”, since this project is an introduction to Sprite Kit actions), and went with all the other default options:

project options

After you choose a place to save your project, you should see the various properties for your new project, which should look something like the screenshot below.

In this project, we’re going to show spaceships flying across the full width of the screen, so we want our app to be landscape-only. The simplest way to restrict our app’s orientation to landscape is by checking and unchecking the appropriate Device Orientation checkboxes in the app’s properties. Make sure that:

  • Portrait is unchecked
  • Landscape Left and Landscape Right are checked

uncheck portrait

Click the screenshot to see it at full size.

You can confirm that the app is landscape-only by running it. It should look like the video below, with spinning spaceships appearing wherever you tap the screen. It shouldn’t switch to portrait mode when you rotate the phone to a portrait orientation:

Your first scene, your first sprite

Let’s dive right in and draw our first sprite on the screen. Open GameScene.swift and replace all its code with the following:

import SpriteKit

class GameScene: SKScene {

  let spaceshipSprite = SKSpriteNode(imageNamed: "Spaceship")

  override func didMoveToView(view: SKView) {
    spaceshipSprite.position = CGPoint(x: 300, y: 300)
    addChild(spaceshipSprite)
  }
  
}

In this example app, we’ll be doing all our coding in GameScene.swift, which contains the GameScene class. GameScene is a subclass of SKScene, the superclass for all scenes. Sprite Kit class names usually begin with the letters SK.

In Sprite Kit, a scene is both:

  • A “canvas” where we draw objects to the screen, such as sprites, and
  • a place for the logic that draws onscreen objects, responds to user input, and deals with the interactions of onscreen objects.

A scene is usually used to correspond to a “screen” in a game. For example, you might use one scene for a game’s title screen, another for gameplay, and a third scene for the “game over” screen. This example app will have just one screen, so we just need one scene: GameScene.

Run the app. You should see something like this:

run 01 - landscape

The spaceship that you see is the onscreen rendering of the spaceshipSprite object, the one property in our GameScene class. It’s an instance of SKSpriteNode, Sprite Kit’s sprite class. It’s declared and instantiated in a single line:

let spaceshipSprite = SKSpriteNode(imageNamed: "Spaceship")

The method that you’ll probably use to instantiate sprite objects most of the time is the init(imageNamed:) method, which takes the name of an image file in the app bundle (in the project’s filesystem) as its argument. The Spaceship image is included in the template that Xcode creates for new game projects, and can be found in the default asset catalog, Assets.xcassets.

Our GameScene class has a single method: didMoveToView. This method is called when the scene is first presented, and at the moment, it contains two lines. Here’s the first one:

spaceshipSprite.position = CGPoint(x: 300, y: 300)

The location of a sprite is determined by its position property, which is a CGPoint, a struct representing a point in 2D space defined by an x-coordinate and a y-coordinate (the CG prefix indicates that it’s from the Core Graphics library).

You’ve probably figured out that this line of code puts the spaceship at the point (300, 300). What you might not know is that (300, 300) means:

  • x-coordinate: 300 points from the left edge of the view
  • y-coordinate: 300 points from the bottom edge of the view

Most programming frameworks treat increasing y-coordinates as going downward, but Sprite Kit is based on OpenGL, which uses the coordinate system used in math, where increasing x goes right, and increasing y goes up:

When setting a sprite’s coordinates, you should keep a sprite’s anchor point — represented by its anchorPoint property — in mind. It’s a CGPoint value that corresponds to the point in a sprite that corresponds to the position in the scene that you assign to it, whose x- and y-coordinates range from 0 to 1 as shown below:

anchor point

The default anchorPoint value for a sprite is (0.5, 0.5), which corresponds to a point in the dead center of the sprite. This means that if we set the sprite’s position to (300, 300), the sprite’s center will be located at (300, 300). If we change the sprite’s anchorPoint to (0, 0), its lower left-hand corner, its lower left-hand corner will be at the coordinates (300, 300), and the rest of the sprite will be above and to the right of that point. On the other hand, if we change the sprite’s anchorPoint to (1, 1), its upper right-hand corner will be at the coordinates (300, 300) and the rest of the sprite will be below and to the left of that point.

The sprite doesn’t actually appear until the second line of the didMoveToView method gets executed:

addChild(spaceshipSprite)

Only sprites that are added as children of a scene appear in the scene.

Scenes, sprites, and nodes

In this tutorial, the only Sprite Kit objects that we’ll be drawing onscreen are scenes and sprites, but it’s worth talking about the larger Sprite Kit framework and how scenes and sprites fit into it.

Most objects in a Sprite Kit-based game that are responsible for putting images on the screen or playing sound are nodes — subclasses of the SKNode class. You’ll probably never have to instantiate an SKNode instance; its purpose is to provide some baseline of behavior and capabilities for its subclasses.

sprite kit nodes

The term “node” implies that there’s a tree structure of some kind, and that’s the case. The scene in a game — represented by the SKScene class — acts as the root node of this tree, and the scene’s child nodes are the ones that appear in it and interact in it. If you want a node like a sprite to appear in a scene, you must add it as a child of that scene.

sprite kit nodes form a tree

Sprites — represented by the SKSpriteNode class — can have child sprites. We’ll cover child sprites in another article, but we’ll say that they’re useful for creating onscreen objects made up of two or more sprites, such in the example above where the mad scientist sprite character has a force field as a child sprite. Just as child sprites of a scene are attached to the parent scene and have a location in their parent scene’s coordinate system, child sprites of a sprite are attached to the parent sprite and have a location in their parent sprite’s coordinate system.

That’s enough big picture discussion for now — let’s get back to coding!

Scaling and rotation

Let’s make a couple of changes to our spaceship sprite. We want to:

  • Scale it down to a quarter of its current size, and
  • Rotate it 90 degrees so that it’s pointing to the right.

This is easily done — just add a couple of lines to didMoveToView so that it looks like this:

override func didMoveToView(view: SKView) {
  spaceshipSprite.position = CGPoint(x: 300, y: 300)
  spaceshipSprite.setScale(0.25)
  spaceshipSprite.zRotation = CGFloat(-M_PI_2)
  addChild(spaceshipSprite)
}

Run the app. You should now see this:

run 02

The setScale method is pretty straightforward. It scales the sprite in both the x- and y-directions by the factor specified in the argument you provide it with, which in this case is 0.25.

The zRotation property specifies rotation around the z-axis. As with most programming languages and frameworks, Sprite Kit requires that you specify angles in radians instead of degrees. It also follows the convention in mathematics where angles increase in the counterclockwise direction:

radians

The standard math library included with Swift comes with a number of π-related constants that you’ll find useful when working with angles:

  • M_PI: π, or 180°
  • M_PI_2: π / 2, or 90°
  • M_PI_4: π / 4, or 45°

The spaceship graphic points upwards, so in order to point it to the right, we need to rotate it 90° clockwise, hence spaceshipSprite.zRotation = CGFloat(-M_PI_2).

The event loop and moving sprites the hard way

Most game frameworks operate in an event loop, which is a repeating cycle based on this general sequence of events:

event loop

The specifics of the event loop vary from game framework to game framework. Here’s what Sprite Kit’s event loop looks like:

sprite kit event loop

Each cycle of the event loop is called a frame. That’s because at the end of each cycle, the currently displayed scene is rendered. By making small changes during each frame and rendering frames several times a second, we create motion, in pretty much the same way that’s it’s done with film and television, which is where the term “frame” comes from — it refers to frames of film:

film frames

As the scene executes the event loop, it calls a number of methods, each of which corresponds to a specific part of the loop. By overriding these methods, we can make our own code execute at specific points of the event loop.

In this application, we’ll override the update method, which gets executed at the start of each frame, immediately after Sprite Kit renders the screen. It’s a good place to define changes to objects in the scene. As a method automatically called by the system every time it goes around the event loop, it takes the argument currentTime, a sub-millisecond-accurate number in seconds that makes it possible to determine the amount of time that has elapsed since the last call to update.

Let’s use it to move the spaceship in a rightward direction by adding the following code to GameScene:

override func update(currentTime: CFTimeInterval) {
  spaceshipSprite.position.x += 10
}

If you run the app, you’ll see the ship start at (300, 300) and move to the right, eventually going off the screen. This method of moving the spaceship around works, but would require you to write a fair bit of code to get this result:

In the app shown above, each spaceship sprite:

  1. Appears on the left edge of the scene at a random y-coordinate and flies across the screen to disappear off the right edge in 5 seconds’ time,
  2. Backs up from the right edge a distance of about a third of the scene over 2 seconds,
  3. Executes a 180-degree counterclockwise turn in 1.5 seconds,
  4. waits 2 seconds, and
  5. Zips off the left edge of the scene in half a second.

Luckily for us, Sprite Kit provides a set of powerful tools that lets us get around the kind of micromanagement that game development once required. They’re called actions, and they’ll let us code the activity shown above in just over two dozen lines of code.

Your first action

Change the code in GameScene so it looks like this:

import SpriteKit

class GameScene: SKScene {

  let spaceshipSprite = SKSpriteNode(imageNamed: "Spaceship")
  
  override func didMoveToView(view: SKView) {
    spaceshipSprite.position = CGPoint(x: -spaceshipSprite.size.width / 2,
                                       y: 300)
    spaceshipSprite.setScale(0.25)
    spaceshipSprite.zRotation = CGFloat(-M_PI_2)
    addChild(spaceshipSprite)
    
    let flyAcrossScreen = SKAction.moveTo(CGPoint(x: size.width +
                                                     spaceshipSprite.size.width / 2,
                                                  y: 300),
                                          duration: 5)
    spaceshipSprite.runAction(flyAcrossScreen)
  }
  
}

Note the changes:

  • We’ve eliminated the update method,
  • the spaceship sprite’s starting x-coordinate is half its width to the left of the left edge of the scene, and
  • we’ve added a couple of lines of code that concern themselves with something named flyAcrossScreen.

Before we discuss the changes, run the app. It should look like this:

Let’s look at why we set the spaceship sprite’s x-coordinate to -spaceshipSprite.size.width / 2. That’s the minimum x-coordinate that ensures that the sprite is far enough to the left so that it’s no longer visible onscreen (remember what we discussed about anchor points earlier):

half spaceship width

Now let’s discuss the more interesting thing: that thing named flyAcrossScreenIt’s an action — represented by the class SKAction — an object that changes something about the structure or properties of a node. There are many types of SKActions, including:

  • Actions that move nodes, either to specific coordinates or in a direction relative to the current position, in a straight line or along a specified path,
  • actions that rotate nodes, either to a specific angle or by a certain angle relative to the current orientation,
  • actions that scale nodes, either to a specific size or by a specific factor relative to the current size, in the x-, y-, or both directions,
  • actions that change the content of a node, either by changing its current appearance, producing an animation effect by rapidly cycling through a set of “frames”, changing its opacity, or colorizing it,
  • actions that play sounds,
  • actions that combine actions, either by executing them in sequence or concurrently,
  • actions that act as pauses or delays,
  • actions that repeat or reverse actions, and
  • actions that execute custom code.

flyAcrossScreen is an instance of an SKAction.moveTo function. This type of function moves a node to a specific point in the scene (in this case, just off the right edge of the screen) in an amount of time specified in seconds (in this case, 5). The function returns an action, which is performed by a node when it is provided as an argument for one of the node’s runAction methods.

Note that in a single line of code:

  • We’ve defined something that moves a sprite to a given coordinate in a given amount of time without having to write any code to manage that movement, and
  • we’ve also stored it in a constant for later use.

Adding another action and introducing action sequences

Let’s try adding another action to the mix, so that after the spaceship has flown off the right edge of the scene, it reappears on the screen by backing up 400 points.

We’ll do this by defining a new action called backUpALittle, using SKAction‘s moveByX(_:y:duration:) method. Unlike moveTo(_:duration:), which moves a node to a specific point in the scene, moveByX(_:y:duration:) moves a node by a number of x- and -y points relative to its current position. Change the code in your didMoveToView method to the code shown below:

override func didMoveToView(view: SKView) {
  spaceshipSprite.position = CGPoint(x: -spaceshipSprite.size.width,
                                     y: 300)
  spaceshipSprite.setScale(0.25)
  spaceshipSprite.zRotation = CGFloat(-M_PI_2)
  
  addChild(spaceshipSprite)
  
  let flyAcrossScreen = SKAction.moveTo(CGPoint(x: size.width +
                                                   spaceshipSprite.size.width,
                                                y: 300),
                                        duration: 5)
  spaceshipSprite.runAction(flyAcrossScreen)
  
  let backUpALittle = SKAction.moveByX(-400,
                                       y: 0,
                                       duration: 2)
  spaceshipSprite.runAction(backUpALittle)
}

If you were to run the app now, you’d see the spaceship fly across the screen, but you won’t see it back up back onto the screen afterwards. If you put some print statements around the runAction method that runs the backUpALittle action, as shown below…

let backUpALittle = SKAction.moveByX(-400,
                                     y: 0,
                                     duration: 2)
print("Commence backing up")
spaceshipSprite.runAction(backUpALittle)
print("Completed backing up")

…you’ll see the lines “Commence backing up” and “Completed backing up” appear in Xcode’s console while the spaceship is still executing the flyAcrossScreen method. Obviously, there’s more to running two or more actions in a sequence than simply running them one after another.

That’s what the SKAction.sequence method is for. Given an array of SKActions, it executes them in the order in which they appear in that array. Change the code in didMoveToView to this:

override func didMoveToView(view: SKView) {
  spaceshipSprite.position = CGPoint(x: -spaceshipSprite.size.width,
                                     y: 300)
  spaceshipSprite.setScale(0.25)
  spaceshipSprite.zRotation = CGFloat(-M_PI_2)
  
  addChild(spaceshipSprite)
  
  let flyAcrossScreen = SKAction.moveTo(CGPoint(x: size.width +
                                                   spaceshipSprite.size.width,
                                                y: 300),
                                        duration: 5)
  let backUpALittle = SKAction.moveByX(-400,
                                       y: 0,
                                       duration: 2)
  let spaceshipActions = SKAction.sequence([flyAcrossScreen, backUpALittle])
  
  spaceshipSprite.runAction(spaceshipActions)
}

When you run the app, you should see this:

Let’s make the sequence a little fancier. We’ll define these actions and then add them to the sequence:

  • doA180: Using SKAction.rotateByAngle, we’ll rotate the spaceship 180 degrees clockwise over a span of 1.5 seconds,
  • wait2Seconds: Using SKAction.waitForDuration, introduce a 2-second pause, and
  • blastOff: Using SKAction.moveTo, blast the spaceship off the left edge of the screen in half a second.

Here’s the code for running all the actions…

let flyAcrossScreen = SKAction.moveTo(CGPoint(x: size.width +
                                                 spaceshipSprite.size.width,
                                              y: 300),
                                      duration: 5)
let backUpALittle = SKAction.moveByX(-400,
                                     y: 0,
                                     duration: 2)
let doA180 = SKAction.rotateByAngle(CGFloat(M_PI), duration: 1.5)
let wait2seconds = SKAction.waitForDuration(2)
let blastOff = SKAction.moveTo(CGPoint(x: -spaceshipSprite.size.width / 2,
                                       y: 300),
                                       duration: 0.5)
let spaceshipActions = SKAction.sequence([flyAcrossScreen,
                                          backUpALittle,
                                          doA180,
                                          wait2seconds,
                                          blastOff])

spaceshipSprite.runAction(spaceshipActions)

…and here’s what the app looks like when you run it:

Spawning multiple spaceships, part one

Let’s harness the true power of actions by changing the code so that we spawn a new spaceship that performs all the actions we defined every time the user taps the screen. Here’s the code:

import SpriteKit

class GameScene: SKScene {
  
  override func didMoveToView(view: SKView) {
    spawnSpaceship(y: 300)
  }
  
  func spawnSpaceship(y yposition: CGFloat) {
    let spaceshipSprite = SKSpriteNode(imageNamed: "Spaceship")
    
    spaceshipSprite.position = CGPoint(x: -spaceshipSprite.size.width / 2,
      y: yposition)
    spaceshipSprite.zRotation = CGFloat(-M_PI_2)
    spaceshipSprite.setScale(0.25)
    addChild(spaceshipSprite)
    
    let flyAcrossScreen = SKAction.moveTo(CGPoint(x: size.width + spaceshipSprite.size.width / 2,
      y: yposition),
      duration: 5)
    let backUpALittle = SKAction.moveByX(-400,
      y: 0,
      duration: 2)
    let doA180 = SKAction.rotateByAngle(CGFloat(M_PI), duration: 1.5)
    let wait2seconds = SKAction.waitForDuration(2)
    let blastOff = SKAction.moveTo(CGPoint(x: -spaceshipSprite.size.width / 2,
      y: yposition),
      duration: 0.5)
    let spaceshipActions = SKAction.sequence([flyAcrossScreen,
      backUpALittle,
      doA180,
      wait2seconds,
      blastOff])
    spaceshipSprite.runAction(spaceshipActions)
  }
  
  override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
      spawnSpaceship(y: touch.locationInNode(self).y)
    }
  }

}

Note the changes that we’ve made:

  • We’ve taken our spaceship setup and action code and put it into its own method, spawnSpaceship, which takes a y-coordinate as an argument,
  • we call spawnSpaceship in the didMoveToView method in such a way that the first spaceship shown onscreen behaves like the one in the previous version of the app, and
  • we respond to touches onscreen with the touchesBegan method. It’s called whenever a user touches down on the screen, and one of the arguments it provides is a Set of UITouch objects. From each of these objects, we can get the y-coordinate of each spot where the user touched the screen, and  we spawn a new spaceship and performing its actions at that y-coordinate. (We’ll cover touch events in greater detail in a later article.)

When you run this app, it looks like this:

Not bad for a couple dozen lines of code!

Spawning multiple spaceships, part two: using the update method as a timer

Let’s change the app so that it in addition to spawning a new spaceship when the user touches the screen, it also automatically spawns a new spaceship at a random y-coordinate every half second. Here’s the code:

import SpriteKit

class GameScene: SKScene {
  
  var lastSpaceshipSpawnTime: CFTimeInterval = 0
  
  override func didMoveToView(view: SKView) {
    spawnSpaceship(y: 300)
  }
  
  override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
      spawnSpaceship(y: touch.locationInNode(self).y)
    }
  }
  
  override func update(currentTime: CFTimeInterval) {
    if currentTime - lastSpaceshipSpawnTime > 0.5 {
      spawnSpaceship(y: CGFloat(arc4random_uniform(UInt32(size.height))))
      lastSpaceshipSpawnTime = currentTime
    }
  }
  
  func spawnSpaceship(y yposition: CGFloat) {
    let spaceshipSprite = SKSpriteNode(imageNamed: "Spaceship")
    
    spaceshipSprite.position = CGPoint(x: -spaceshipSprite.size.width / 2,
      y: yposition)
    spaceshipSprite.zRotation = CGFloat(-M_PI_2)
    spaceshipSprite.setScale(0.25)
    addChild(spaceshipSprite)
    
    let flyAcrossScreen = SKAction.moveTo(CGPoint(x: size.width + spaceshipSprite.size.width / 2,
      y: yposition),
      duration: 5)
    let backUpALittle = SKAction.moveByX(-400,
      y: 0,
      duration: 2)
    let doA180 = SKAction.rotateByAngle(CGFloat(M_PI), duration: 1.5)
    let wait2seconds = SKAction.waitForDuration(2)
    let blastOff = SKAction.moveTo(CGPoint(x: -spaceshipSprite.size.width / 2,
      y: yposition),
      duration: 0.5)
    let spaceshipActions = SKAction.sequence([flyAcrossScreen,
      backUpALittle,
      doA180,
      wait2seconds,
      blastOff])
    spaceshipSprite.runAction(spaceshipActions)
  }
  
}

Note the changes:

  • We’ve introduced a new property to the GameScene class: lastSpaceshipSpawnTime, a CFTimeInterval variable to keep track of when the spawnSpaceship method was last executed.
  • We’ve brought back the update method. It gets called often enough that we can use it to hold some code to call spawnSpaceship at intervals very, very close to every half second.

Here’s what the app looks like when you run it:

The spaceships spawn every half second, but doing so requires us to write some code and declare a property in order to manage the spawning process. Isn’t there an action that do the management for us?

Spawning multiple spaceships, part three: Using actions to manage the entire process

In this version of our spaceship-spawning app, we’ll make use of two new actions:

Change the code so that it looks like this:

import SpriteKit

class GameScene: SKScene {
  
  override func didMoveToView(view: SKView) {
    spawnSpaceship(y: 300)
    
    let addAnotherShip = SKAction.runBlock {
      self.spawnSpaceship(y: CGFloat(arc4random_uniform(UInt32(self.size.height))))
    }
    let waitAHalfSecond = SKAction.waitForDuration(0.5)
    let addShipThenWait = SKAction.sequence([addAnotherShip, waitAHalfSecond])
    let addShipsAdInfinitum = SKAction.repeatActionForever(addShipThenWait)
    runAction(addShipsAdInfinitum)
  }
  
  override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
      spawnSpaceship(y: touch.locationInNode(self).y)
    }
  }
  
  func spawnSpaceship(y yposition: CGFloat) {
    let spaceshipSprite = SKSpriteNode(imageNamed: "Spaceship")
    
    spaceshipSprite.position = CGPoint(x: -spaceshipSprite.size.width / 2,
                                       y: yposition)
    spaceshipSprite.zRotation = CGFloat(-M_PI_2)
    spaceshipSprite.setScale(0.25)
    addChild(spaceshipSprite)
    
    let flyAcrossScreen = SKAction.moveTo(CGPoint(x: size.width + spaceshipSprite.size.width / 2,
                                                  y: yposition),
                                          duration: 5)
    let backUpALittle = SKAction.moveByX(-400,
                                         y: 0,
                                         duration: 2)
    let doA180 = SKAction.rotateByAngle(CGFloat(M_PI), duration: 1.5)
    let wait2seconds = SKAction.waitForDuration(2)
    let blastOff = SKAction.moveTo(CGPoint(x: -spaceshipSprite.size.width / 2,
                                           y: yposition),
                                   duration: 0.5)
    let spaceshipActions = SKAction.sequence([flyAcrossScreen,
                                              backUpALittle,
                                              doA180,
                                              wait2seconds,
                                              blastOff])
    spaceshipSprite.runAction(spaceshipActions)
  }
  
}

Let’s look at the changes:

  • We got rid of the update method. We don’t need it to function as a timekeeper, as we’re using actions to manage the spaceship spawning process.
  • In didMoveToView, we define a set of actions that will end up managing the task of spawning spaceships:
    • First, we define addAnotherShip as a runBlock action that calls the spawnSpaceship method. Remember that in closures, you have to be explicit when referring to methods and properties of the containing class, which is why there’s an explicit use of self.
    • We define waitAHalfSecond as a waitForDuration action, which we’ll use to create the half-second delay between spaceship spawnings.
    • We create addShipThenWait as a sequence of addAnotherShip followed by waitAHalfSecond. By now, you can probably see where we’re going with this.
    • Then we define addShipsAdInfinitum as a repeatActionForever action that performs addShipThenWait over and over and over again.
    • And finally, we have the scene (remember, it’s a node, so it too can run actions) run the addShipsAdInfinitum action. From this point on, we no longer have to worry about spawning those spaceship sprites — we’ve got actions to do that!

Here’s what it looks like when you run it:

Not bade for 26 lines of code, and that includes the line import SpriteKit!

What we just covered

In this article, we covered:

  • Starting a new Game project in Xcode
  • Restricting an app’s orientation to landscape-only
  • Drawing sprites at a specified location on the screen
  • Screen coordinates in Sprite Kit
  • Anchor points in sprites
  • Nodes, scenes, sprites, and how they’re related
  • Scaling and rotating sprites
  • The event loop and the update method
  • Moving sprites by writing code to update their position
  • Moving sprites by using the moveTo and MoveBy actions
  • Performing multiple actions in sequence using sequence actions
  • Rotating sprites using the rotateByAngle action
  • Introducing a delay for action sequences with the waitForDuration action
  • Responding to touches on the screen with the touchesBegan method
  • Using the update method as a timer to perform tasks at specific intervals
  • Running code as an action using the runBlock action
  • Repeating actions indefinitely using the repeatActionForever action
  • Using actions to reduce the amount of code we have to write to manage multiple onscreen objects

We’ll expand on this material and work towards building an actual game in the following articles in this series.

Categories
Uncategorized

I’ll bet I can gain access after two dozen tries

well-worn pinpad

With a very lucky guess, I have actually pulled this off once in two tries, and got many free beers by people stunned by my “elite hacker skills”.

My assertion that it would take me 24 (4 × 3 × 2 × 1) attempts to enter the correct keycode is based on a few reasonable assumptions:

  • the keycode is 4 digits long, as many are (people complain if you try to make them longer)
  • I can try three keycodes at a time without locking myself out of more attempts, wait a couple of minutes, and try another three keycodes, wait a couple of minutes, and so on, and
  • the wear marks on the keypad are real and not a ruse to throw off would-be thieves.

It might be interesting to use fake wear marks on a keypad as a kind of honeypot. You could have the system send an alert if someone kept entering keycodes that were permutations of numbers corresponding to the keys with fake wear.

Categories
Uncategorized

A $30 – $50 off deal on the 4th-gen Apple TV from an apparently undead Radio Shack

Screen shot: RadioShack's page for their 32gb Apple TV special.

Click the screen shot to visit the page.

In case you missed the Black Friday/Cyber Monday specials on the 4th-generation Apple TV — that’s the one that runs apps and you can do development work on — there’s another sale going on right now. RadioShack (who apparently aren’t dead and have compressed their name into a single intra-capped word) are currently offering:

If you want to buy the Apple TV for app development…

usb-a to usb-c cable

If you plan on developing apps for the Apple TV, you should note that the Apple TV doesn’t come with a key piece of cabling: a USB-A male to USB-C male cable, which you need to deploy apps from your Mac (into which you plug the USB-A side of the cable) and the Apple TV (into which you plug the USB-C side). For reasons known only to Sir Jony Ive, they went with a USB-C port instead of a Lightning one.

They’re still hard to find at stores. Don’t add RadioShack’s $25 one to your order. Shop around online for deals like the one currently at GearBest, who are selling them for $3.

Categories
Uncategorized

Snoop Dogg files the most gangsta bug report ever

Annoyed by the January 13, 2016 XBox Live outage, gangsta rapper Calvin Broadus, Jr., better known as Snoop Dogg (is he not going by Snoop Lion anymore?), took to Instagram to vent. It’s in the video above, and be warned, he cusses, as one does when angry and keepin’ it real.

A couple of thoughts:

  • I get the feeling that for the next little while, a number of bug reports and unit testing failure messages will end with the line “Fix yo’ shit, man!”
  • This is an amazing example of William Gibson’s line “the street finds its own uses for things”.
Categories
Uncategorized

As PC sales hit an eight-year low, we’re living in the mobile era

downward pc trend

Gartner announced that worldwide PC shipments dropped considerably in 2015:

  • Shipments for the fourth quarter of 2015 were 75.7 million units, an 8.3% drop from the number shipped in 4Q 2014, and
  • shipments for the entire year of 2015 were 288.7 million units, an 8% drop from the number shipped for all of 2014.

Their preliminary 2015 shipment estimates for vendors worldwide show that the top 6 vendors by shipment all experienced a drop in shipments (randing from 3% to 11%) with one notable exception — Apple, who say a nearly 3% growth:

worldwide pc shipments 4q14 vs 4q15

Click the graph to see it at full size.

In the United States, vendors fared a little better. While the top two vendors, HP and Dell, saw shrinkage (especially HP, whose 4Q shipments dropped 8.5 from the previous year’s number), Apple and Lenovo made significant gains (a decent 6.5% and a stunning 21.1%, respectively), and Asus stayed even:

us pc shipments 4q14 vs 4q15

Click the graph to see it at full size.

We’ve been seeing this trend for some time. Global PC sales peaked in 2011 with just over 365 million units, and since then, sales have been cooling at an average rate of just under 6% per year:

global pc sales 8-year low

Click the graph to see it at full size.

IDC have released similar numbers, but their reported drop in worldwide PC shipments is even bigger: 10.6%, with the observation that “he year-on-year decline in 2015 shipments was nevertheless the largest in history, surpassing the decline of -9.8% in 2013.”

IDC cites a number reasons for the drop in PC shipments, which include:

  • Longer PC lifecycles,
  • falling commodity prices and weak international currencies,
  • “social disruptions” in EMEA and Asia/Pacific that affected foreign markets, and
  • last, but certainly not least, competition for technology consumer dollars from mobile devices, even though their growth has been reduced to single digits.

PC sales are now dwarfed by smartphone sales these days — the PCs sold in all of 2015 don’t even amount to as much as the smartphones sold on average for any given quarter of 2015. Here’s how many PCs and smartphones shipped in the previous quarter:

worldwide pc shipments vs smartphone shipments

Click the graph to see it at full size.

And to further drive home the point that it’s an increasingly mobile world, here’s Horace Dediu’s recent tweet, in which he declares that iOS alone — never mind Android — overtook Windows last year:

We’re well and truly living in the mobile era.

this article also appears in the GSG blog

Categories
Florida Tampa Bay

Tampa iOS Meetup, Tuesday, January 19th: Get started with making iOS games with Sprite Kit!

Poster: Get Your Game On! / Getting started with building iOS games in Sprite Kit / Tampa iOS Meetup - Tuesday, january 19, 2016 -- A hodgepodge of iOS gaming-related imagery.

Happy new year, experienced and aspiring iOS developers in the Tampa Bay area!

If you’ve made a new year’s resolution to take up iOS, Swift, or game development in 2016, the upcoming Tampa iOS Meetup topic might be just what you need to get started. It’s called Get Your Game On: Getting Started with Sprite Kit, and it’s taking place in Tampa next Tuesday, January 19, 2016.

Tampa iOS Meetup banner with photo of Joey deVilla and Angela Don in the background.

Tampa iOS Meetup is a monthly meetup run by local mobile developer/designer Angela Don and Yours Truly. While Tampa has a couple of great iOS developer meetups — Craig Clayton’s Suncoast iOS and Chris Woodard’s Tampa Bay Cocoaheads, we figured that there was room for a third iOS meetup in the Tampa Bay area, and especially one that would stray into other areas of mobile development. So we made one.

Tampa iOS Meetup’s next meetup: Get Your Game On!

Icons of iOS games appearing to leap off the screen of an iPhone.

“Games” is the most popular category in the iOS App Store, accounting for 22.5% of active apps. They’re more than twice as popular as the next-most-popular category, business apps. Look in any place where people are waiting these days — in line at the bank or grocery, at public transit stops and airports, cafes and restaurants — and you’ll see people passing the time with a mobile game. Gaming is a basic human activity — we’ve had them since our earliest days, and we’ve had computer games for almost as long as we’ve had computers.

Despite the fact that games are the most-used type of mobile app, there are far fewer game development tutorials than there are for “standard” apps. That’s a pity, because one of the best ways to learn programming is satisfaction, and there’s nothing more satisfying than seeing a game you created in action. While games can be complex, the concepts behind them are simple, and some of the most popular games are pretty simple as well. Why not try game development as a way to learn programming, Swift, and iOS?

Animated scene showing 'Flappy Bird' gameplay.

Join us next Tuesday, January 19th at the Tampa iOS Meetup and start the new year by getting your game on!

The Details

  • What: Tampa iOS’ Meetup’s “Get Your Game On” session. Please sign up on our Meetup page so we can plan accordingly!
  • When: Tuesday, January 19, 2016, 6:30 p.m. – 9:30 p.m. We’ll have some snacks at 6:30, with the presentation beginning at 7:00.
  • Where: Energy Sense Finance, 3825 Henderson Boulevard (just west of Dale Mabry), Suite 300. See the map below.
  • What to bring: Yourself, but if you’d like to follow along, bring your Macbook and make sure it’s got Xcode 7.2.
  • What to read in advance: If you’re one of those people who likes to do some readings ahead of a presentation, check out the Sprite Kit tutorials on Ray Wenderlich’s site. We’ll be using our own tutorial material, but Ray’s stuff will come in handy.
Categories
Uncategorized

Mobile developer news roundup #1: The phablet era, UX lessons from restaurants, Evernote’s 5% problem, Android and OpenJDK, and Solitaire’s secret history

We’re in the phablet era now

Chart: Time spent on mobile grows 117% year over year.

Click the graph to see it at full size.

Venture capitalist Fred Wilson looked at research firm Flurry’s State of Mobile 2015 report and took note of the chart above, which shows that the greatest growth in time spent on mobile came from “phablets” — those large phones that blur the line between phone and tablet — and wrote:

There’s not a lot new in this data to be honest, but it confirms a lot of what everyone believes is happening. We are converging on a single device format in mobile and that’s driving some important changes in usage. We are in the phablet era.

Everything I needed to know about good user experience I learned while working in restaurants

Waiter and cook working in a restaurant.

At the Neilsen/Norman Group’s blog, Everything I Needed to Know About Good User Experience I Learned While Working in Restaurants lists the many things that you can learn from restaurants and apply to your applications, from designing for both new and expert users to interaction design and error handling to community management.

If you’re not familiar with the Nielsen/Norman Group, they’re the “Monsters of Rock” of user interface and experience. Their principals are:

The cautionary lessons of Evernote’s “5% problem”

An out-of-focus Evernote icon.

Evernote used to be my go-to note-taking app in 2011. I worked across platforms, and I loved that I could start a note on my laptop, continue on my iPad, and then later make tweaks or addenda on my phone. But as time went by, it got buggier and increasingly less usable to the point where I abandoned it worse and buggier until I abandoned it in annoyance.

Their note-taking app got buggier as the company tried to expand so that they had offerings that would appeal to as many people as possible. Therein lay their problem: as their own former CEO put it, people at Evernote conferences would go up to him and say that they loved the platform, but used only 5% of what it could do. The problem was that there was a different 5% for every person. They spread themselves too thin, lost their focus, started half-assign their product lines, and in an attempt to please everyone, ended up annoying them.

Keep calm and carry on developing Android apps

The classic 'Keep Calm and Carry On' poster.

You may have heard that the ongoing legal battle between Oracle (who own Java) and Google (who own Android, which is Java-based) has led to Google’s decision to move from their proprietary version of the JDK to Oracle’s OpenJDK. You may be concerned, but you probably shouldn’t be. It may cause headaches for Google and Android mobile phone vendors, but as Android developers, it shouldn’t really affect you.

As Android developer and online tutor Tim Buchalka puts it:

We write our code accessing the same libraries, and things just work. Of course its going to be a decent chunk of work for Google to get this all working so that we dont have to worry about it, but if anyone has the resources to do it, Google do.

What do you need to do as an Android developer? Absolutely nothing, its business as normal! You dont need to change anything in your development process and it may well be that when Android N arrives you won’t have to either. So fire up Android Studio, and get back to coding!

A story you might not know about Microsoft Solitaire: it was created by a summer intern!

Screen shot of Microsoft Solitaire on Windows 3.1

Is Wes Cherry a bit annoyed that he never got paid to write one of the most-used applications of the Windows 3.x/9x days? He once answered “Yeah, especially since you are all probably paid to play it!”