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.
\$\begingroup\$
\$\endgroup\$
1
-
\$\begingroup\$ I don't work with libgdx but I understand your problem.In unity when you want filter collisions you can use trigger,this is mean you can true trigger when collision happened for example:when tank collide with rocket false collision. aurelienribon.com/blog/2011/07/… ----------- in unity there is ignore collision docs.unity3d.com/ScriptReference/Physics2D.IgnoreCollision.html \$\endgroup\$– Seyed Morteza KamaliCommented Feb 2, 2016 at 5:01
Add a comment
|
1 Answer
\$\begingroup\$
\$\endgroup\$
2
You can use the filter
on the FixtureDefinition
s 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\$ Commented Feb 2, 2016 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\$ Commented Feb 2, 2016 at 16:22