newmanne
newmanne

Reputation: 2089

Box2D detect collisions without causing a collision between certain pairs of objects

I am developing a game using box2d and libgdx. I have a character that is a ball that bounces off of walls. There are enemies that kill the player - they also bounce off walls. I am trying to make an invincibility power up such that when the player is invincible, the player should plow through enemies (and not collide off of them), and destroy them. This means I need to be notified of the collision between the player and the enemy (in order to destroy the enemy), but the collision should not take place (the player should not bounce off of the enemy). My question is: what would be the best way to implement this?

I don't think sensors would work, because the player and the enemies still need to collide with the walls, so making either one a sensor wouldn't solve the issue. I don't think collision bit masks will work, because I still need to generate a collision event when the player and the enemy collide.

Thanks

Upvotes: 1

Views: 734

Answers (2)

cavpollo
cavpollo

Reputation: 4308

Like Dennis said, you could do this easily with sensors. Your body will not phisically collide with other bodies but it will register the collition. You can even specify if they are in the same collision category/group using filters, to be more specific about which bodies collide with each other.

FixtureDef myFixtureDef = new FixtureDef();
CircleShape myCircle = new CircleShape();
myCircle.setRadius(myRadius);
myFixtureDef.shape = myCircle;
myFixtureDef.isSensor = true;
myFixtureDef.filter.categoryBits = = 0x0002; // 0000000000000010 in binary
myFixtureDef.filter.maskBits = 0x0001; // 0000000000000001 in binary
myBody.createFixture(myFixtureDef);

In this example, your body belongs to the 0x0002 category/group and will only collide with the bodies that match the 0x0001 category/group.

Upvotes: 0

Dennis Korbar
Dennis Korbar

Reputation: 500

Sensors can work for you. You could create two fixtures for your player instead of one.

  • Create one fixture for the player that collides with the wall (and not the enemy)
  • Create another fixture for the player that collides with enemies (and not the wall)

Then you simply set the fixture that collides with the enemies to sensor when the invincible power up is active.

Upvotes: 2

Related Questions