0
votes

I have two bodies. One circle with a ball inside and one bird with a polygon. I am trying to detect collision between the sprites within the bodies and not the bodies themselves as in the code snippet below.

 @Override
 public void beginContact(Contact contact) {
Body a = contact.getFixtureA().getBody();
Body b = contact.getFixtureB().getBody();

if(contact.isTouching()){ 
    System.out.println(contact.isTouching());
    if (a.getUserData() == Constants.Enemy || b.getUserData() == Constants.Enemy) {
        System.out.println("yes");
    } 
  }
}

the method above prints out "yes" when the bodies are in a stage as on the picture below which is not right because the sprites have not touched with each other. Any ideas?

enter image description here

2
If the shape of the bird is the rectangle drawn, then it is true that the bodies indeed touch. You would have to choose a more fitting body for the bird than a needlessly large rectangle, some polygon perhaps.kajacx
you are checking collison on body collide or not you have to check for sprite collision. if body collided then check sprite also collide or notSinghak

2 Answers

0
votes

there is probably another way of doing, but if I wanted more accurately, would use this tool -> http://www.aurelienribon.com/blog/projects/physics-body-editor/

If you experience any initial error you can look at these questions might be errors with charger -> Physics Body Editor error

or this BodyEditorLoader - noSuchMethod in this response, public use the charger that works well for me in libgdx (1.5.x)

I hope to help

Update:

you said: "thanks for this but I am not sure whether this will help me in my case. "

Box2d initially assuming that knows nothing of your sprite, position or anything. He "box2d" just knows fixtures ect. If your sprite does not match the size of the fixture, does not know, is not malfunctioning, but you expect something different.

So using the tool, I said, you can adjust the fixture friendlier way to the shape of sprite.

This is an image simulating as could be, the fixture is an image in Gimp, it's just to see the idea:

enter image description here

0
votes

Like Angel Angel said,

Box2D has bounding volumes to detect collisions, which are not pixel perfect and do not know anything about the Sprite itself. This is for a reason of performance, since collision detecting has a huge impact on performance.

The solution is to make the bounding box more accurate. You can use PolygonsShapes or make your bounding rect smaller.

In your case i would consider using a PolygonShape.