Box2d Collision Checking

Problem

I found that when I had box 2d collisions, sometimes object x collides with object y and sometimes it's the other way around. In that I mean that sometimes object x was bodyA and sometimes object y was bodyA.

This caused me to have a collision detection code like this:

        if(bodyA.CollisionType == 0){ // -------- Plaform collides with...
            if(bodyB.CollisionType == 1){ // --- Player
                playScene.Player.OnPlatform = false;
                playScene.Player.OnWall = false;
            }
        }else if(bodyA.CollisionType == 1){ // -------- Player collides with...
            if(bodyB.CollisionType == 0){ // --- Plaform
                playScene.Player.OnPlatform = false;
                playScene.Player.OnWall = false;
            }else if(bodyB.CollisionType == 7){ // --- Wall
                playScene.Player.OnWall = false;
            }
        }else if(bodyA.CollisionType == 7){ // ---------Wall Collides with...
            if(bodyB.CollisionType == 1){ // --- Player
                playScene.Player.OnWall = false;
            }
        }

Solution

Having to check both ways and duplicating code was a pain, I've now cleaned it up using exclusive or's like so:

        if((bodyA.CollisionType == 1 ^ bodyA.CollisionType == 0) &&
            bodyB.CollisionType == 1 ^ bodyB.CollisionType == 0){
            playScene.Player.OnPlatform = false;
            playScene.Player.OnWall = false;
        }else if((bodyA.CollisionType == 1 ^ bodyA.CollisionType == 7) &&
                  bodyB.CollisionType == 1 ^ bodyB.CollisionType == 7){
            playScene.Player.OnWall = false;
        }

This way I don't have to write the same code twice and it's easier to read. Not to mention the fact that a couple times I changed one version of the code, but forgot to change the flipside.

* Note: CollisionType is a field that I added to the Body class, it's not normally in there *

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License