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
, the value would need to be 32
. Always remember to double subsequent values to create unique bitmasks that perform as expected in the physics tests.
Bitmasks are binary values that the CPU can very quickly compare to check...