Book Image

Swift by Example

By : Giordano Scalzo
Book Image

Swift by Example

By: Giordano Scalzo

Overview of this book

Table of Contents (15 chapters)

Making the components interact

Although the app is colorful and seeing the bird fly is fun, we need to create a scene like the real world, where collision with an obstacle typically brings you to a halt.

Setting up the collision detection engine

The SpriteKit physics engine provides us with a really simple mechanism to detect collisions between objects. Basically, we need to set a bitmask for each component, and then a collision detection delegate. Let start defining the bitmask; for it, we define an enumeration in GameScene:

enum BodyType : UInt32 {
    case bird   = 1  // 0b0001
    case ground = 2  // 0b0010
    case pipe   = 4  // 0b0100
    case gap    = 8  // 0b1000

Pay attention to two things: the first is that we must define the bitmask as a power of 2; so that we can detect what touches what, using a bitwise or operation. The second is that we've added a gap identifier, a component we haven't defined yet.

The gap is the hole between two pipes, and we need to detect the moment when...