Question

I am declaring various bitmask categories in my code as follows:

static const uint32_t playerCategory = 1; 
static const uint32_t enemyCategory = 2; 

My game is working perfectly fine using these categories.

However, various sample projects and tutorials define the bitmask values like so:

static const uint32_t playerCategory = (0x01 << 1); // 0010
static const uint32_t enemyCategory = (0x01 << 2); // 0010

QUESTION

Why is this method (bitwise shift) used to declare these values? Also, which method is best for declaring these values, as well as for comparing them in the contact delegate?

Was it helpful?

Solution

I'd do neither of these.

I'd actually create an NS_OPTIONS typedef for it. Something like...

typedef NS_OPTIONS(uint32_t, MyPhysicsCategory)
{
    MyPhysicsCategoryAnt = 1 << 0,
    MyPhysicsCategoryFood = 1 << 1,
    MyPhysicsCategoryMouse = 1 << 2,
};

There is really no difference between what these do. They all just define ints and values of 1, 2, 4, 8, 16, etc...

The difference is in the readability.

By using the NS_OPTIONS way it tells me (and anyone else using my project) that you can use bitwise operations on them.

ant.physicsBody.contactTestBitMask = MyPhysicsCategoryMouse | MyPhysicsCategoryFood;

I know that this means that the ant will be contacted tested against food and mice.

OTHER TIPS

If you define your categories using integers (UInt32):

static const uint32_t playerCategory = 1; 
static const uint32_t enemyCategory = 2; 

you have to remember the sequence 1, 2 ,4, 8, 16, 32, 64 etc all way up to 2,147,483,648.

If you use bit shifts:

static const uint32_t playerCategory = (0x01 << 1); // 0010
static const uint32_t enemyCategory = (0x01 << 2); // 0010

(which should start with a 0 shift), then you can just increment the shifts:

static const uint32_t playerCategory = (1 << 0); 
static const uint32_t enemyCategory = (1 << 1);
static const uint32_t enemy2Category = (1 << 2);
static const uint32_t enemy3Category = (1 << 3);
static const uint32_t asteroidCategory = (1 << 4);
static const uint32_t spaceshipCategory = (1 << 5);
static const uint32_t blackHoleCategory = (1 << 6);
static const uint32_t deathStarCategory = (1 << 7);
.
.
.
static const uint32_t lastCategory = (1 << 31);

which you might find less confusing.

But the net result is the same - you can use bit operations on them no matter how they are defined, as long as they are UInt32, and in your code, you normally never refer to the integer values again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top