Using category masks in Swift

Apple's Adventure game demo provides a good implementation of bitmasks in Swift. You can download Apple's latest demo SpriteKit games from https://developer.apple.com/spritekit/. We will follow their example and use an enum to store our categories as UInt32 values, writing these bitmasks in an easy-to-read manner. The following is an example of a physics category enum for a theoretical war game:

enum PhysicsCategory: UInt32 { 
    case playerTank = 1 
    case enemyTanks = 2 
    case missiles = 4 
    case bullets = 8 
    case buildings = 16 
} 

It is very important to double the value for each subsequent group; this is a necessary step if you want to create proper bitmasks for the physics simulation. For example, if we were to add fighterJets ...

Get Swift Game Development - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.