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 it a real game

The first thing we must implement to make this a real game is collision detection. Then we'll add an end to the game, otherwise it will be really boring. Finally, the usual juiciness will make the game more appealing.

Detecting collisions

Collision detection in SceneKit is implemented as it is in SpriteKit. For every node that can collide, we must create a physics body and attach it to the node, setting a unique identifier for that body. Finally, a contact delegate will receive a call when a collision is detected.

First of all, we define an enumeration to list all the possible types of bodies, which are only two in our case:

enum BodyType : Int {
    case jetfighter = 1  // (1 << 0)
    case cube       = 2  // (1 << 1)

In createJetfighter(), we create a parallelepiped to act as a physics body for the jet fighter, because using the actual model we used for rendering is a waste of calculation resources. For the purpose of detecting a collision, a rough shape...