Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Swift By Example

You're reading from   Swift By Example

Arrow left icon
Product type Paperback
Published in Jun 2015
Publisher
ISBN-13 9781785284700
Length 284 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Giordano Scalzo Giordano Scalzo
Author Profile Icon Giordano Scalzo
Giordano Scalzo
Arrow right icon
View More author details
Toc

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...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image