I have my character fixture and body(is a tank), so when I press the screen it throws a rocket(which also has a body and a fixture) that the player can controlll touching the screen. My game also has coins, which are dropped from boxes, when I destroy them, I don't want the rocket to collide with the tank, because the player can guide it anywhere(even to the tank), and it only get destroyed when touching an enemy. The problem here is that the rocket can touch a coin and move it, but it wouldn not happen. I've read that this can be solved using collision filtering, but I didn't understand very much this concept. I want the tank to collide with the coins, but not with the rocket, which should not collide with the coins.


You can use the filter on the FixtureDefinitions to define what type of objects can collide with what.

You define a category bit-pattern, this describes what the fixture is. Then you define a set of categories that the fixture collides with.

For example;

class PhysicsConstants {
  // Categories
  public static final int CAT_SHIP   = 1;
  public static final int CAT_ROCKET = 2;
  public static final int CAT_COIN   = 4;

  // Collision masks
  public static final int MASK_SHIP = CAT_COIN; // This means a ship only collides with coins
  public static final int MASK_ROCKET = CAT_ROCKET | CAT_COIN; // Rockets collides with other rocket and coins, but not with ships

And then when you create your Body and its FixtureDef you set the bits on the filter;

public FixtureDef createRocketFixture(Shape shape) {
  FixtureDef fd = new FixtureDef();
  fd.shape = shape;
  fd.friction = 1.0f; // or whatever
  fd.density = 1.0f;  // or whatever

  fd.filter.categoryBits = PhysicsConstants.CAT_ROCKET; // I am a rocket fixture!
  fd.filter.maskBits = PhysicsConstants.MASK_ROCKET; // This describes what I can collide with
  • \$\begingroup\$ Can I do this using groupIndex? \$\endgroup\$ – Asaltaviejas Feb 2 '16 at 14:55
  • \$\begingroup\$ @Asaltaviejas It depends on what should be able to collide with what. If two group indexes are different the implementation falls back on the category and mask bits anyway. In my opinion it is easier to just use the masks and categories. \$\endgroup\$ – bornander Feb 2 '16 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.