& bitwise help

larswik

macrumors 68000
Original poster
Sep 8, 2006
1,552
11
I am learning Sprite Kit and dealing with collisions of objects. I got this snippet of code from the Apple Docs and I am trying to figure out what the &bitwise operator is doing. First time using bitwise. I know the && logic operator evaluates left and right side for a true or false.

Is it checking left and right to make sure both are not equal to 0?
Code:
static const uint32_t landerCatagory = 0x1;
static const uint32_t rockCatagory = 0x1 << 1;
static const uint32_t photonCatagory = 0x1 << 2;
static const uint32_t edgeCatagory = 0x1 << 3;

-(void)didBeginContact:(SKPhysicsContact *)contact{
    SKPhysicsBody *firstBody;
    SKPhysicsBody *secondBody;
    
    if (firstBody.categoryBitMask < secondBody.categoryBitMask) {
        firstBody = contact.bodyA;
        secondBody = contact.bodyB;
    }
    else{
        firstBody = contact.bodyB;
        secondBody = contact.bodyA;
    }
    [B]
    if ((firstBody.categoryBitMask & photonCatagory) != 0) [/B]{
        NSLog(@"Big bada boom");
    }
    
    NSLog(@"contact");
}
 

larswik

macrumors 68000
Original poster
Sep 8, 2006
1,552
11
OK, I see what is happening there. Thanks for the reply.

-Lars
 

robvas

macrumors 68030
Mar 29, 2009
2,801
371
USA
Also, a bitmask is a way of using every bit in a value to test for true or false.

Instead of doing

int Thing1True = 1; // 0000 0000 0000 0001
int Thing1False = 0; // 0000 0000 0000 0000
int Thing2True = 1; // 0000 0000 0000 0001
int Thing2False = 0; // 0000 0000 0000 0000
int Thing3True = 1; // 0000 0000 0000 0001
int Thing3False = 0; // 0000 0000 0000 0000

(you're 'wasting' all those bits)

You can do stuff like bit-shifting and bit masks to set each individual bit in an int. So then you can fit 32 or 64 'true/false' in a single variable instead of 32 or 64 separate variables! It was more common in the old day when computers didn't have gigabytes of RAM.

More info:

http://stackoverflow.com/questions/18591924/how-to-use-bitmask
 

larswik

macrumors 68000
Original poster
Sep 8, 2006
1,552
11
Thanks. I needed to learn this for the Sprite Kit. They use bit masks to check for collisions. Sprite Kit uses a method didBeginContact:(SKPhysicsContact *)contact{} to identify which objects collided. That took a day to understand what was going on.

Although I read the Learn C on Mac book (great book) somethings just didn't sync in. I tried to get in to the C class at city college this semester but it was full. Even though I am learning Swift now I still think C is a core language that I should have down.