Search code examples
javalibgdxbit-manipulationgame-physicsbitmask

Box2d filter (maskbits and categorybits)


I searched multiple times but I'm not sure why my contact filtering is not working. I used libgdx to create this simple game. The code is as follows:

public static final short BORDER_CATEGORY_BITS = 0x0001;
public static final short PLAYER_CATEGORY_BITS = 0x0002;
public static final short ENEMY_CATEGORY_BITS = 0x0003;
public static final short FOOD_CATEGORY_BITS = 0x0004;

public static final short BORDER_MASK_BITS = PLAYER_CATEGORY_BITS;
public static final short PLAYER_MASK_BITS = BORDER_CATEGORY_BITS | ENEMY_CATEGORY_BITS;
public static final short ENEMY_MASK_BITS = PLAYER_CATEGORY_BITS;
public static final short FOOD_MASK_BITS = PLAYER_CATEGORY_BITS;

I want player to hit the border and enemies, enemies hitting only player and nothing else, but I have a game loop that adds an enemy every 3 secs, and they go at different speeds and are hitting each other. I haven't really worked with the food so you can ignore that.


Solution

  • Your ENEMY_CATEGORY_BITS is wrong.
    0x0003 is actually 0x0001 | 0x0002. That means you are saying

    ENEMY_CATEGORY_BITS = BORDER_CATERGORY_BITS | PLAYER_CATERGORY_BITS
    

    So you say Enemy is a Player and a Border and as Player collides with Border, Enemy will collide with Border to.

    To set the bits correct, you need to use power of 2s, like 1, 2, 4, 8, 16, 32...

    Also always make sure, that both objects collide with each other, if Player collides with Border, but Border does not collide with Player, there won't be a Player-Boreder-Collision.
    I suggest you to read the iForce2D Box2D tutorials