Search code examples
iossprite-kitbitmaskskphysicsbodyskphysicsworld

Setting of physicsBody category bitmask values


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?


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.