I'm developing a game with LibGDX using Box2D. I'm a newbie, so I've been following Brent Aureli's tutorial in which he creates a class that implements ContactListener in order to detect all the collisions and switch depending on the contact.
I think it's a bit excessive as I don't want to detect all the collisions but only a few in certains bodies.
Is there a way to implement the ContactListener only in a certain body? If not, is there a better way to resolve the collisions more efficiently?
In a Box2D ContactListener the BeginContact method will be called every time a contact initiates whether you have code in there to process it or not.
As an example, the below code is an Excerpt from a ContactListener from one of my projects.
@Override
public void beginContact(Contact contact) {
//System.out.println("Contact");
Fixture fa = contact.getFixtureA();
Fixture fb = contact.getFixtureB();
if(fa.getBody().getUserData() instanceof Brick){
this.brickHit((Brick) fa.getBody().getUserData(), fb);
}else if(fb.getBody().getUserData() instanceof Brick){
this.brickHit((Brick) fb.getBody().getUserData(), fa);
}
if(fa.getBody().getUserData() instanceof Pad){
this.padHit((Pad) fa.getBody().getUserData(), fb);
}else if(fb.getBody().getUserData() instanceof Pad){
this.padHit((Pad) fb.getBody().getUserData(), fa);
}
if(fa.getBody().getUserData() instanceof Bin){
objectInVoid(fb);
}else if(fb.getBody().getUserData() instanceof Bin){
objectInVoid(fa);
}
if(fa.getBody().getUserData() instanceof Ball){
ballHitSomething((Ball) fa.getBody().getUserData(),fb);
}else if(fb.getBody().getUserData() instanceof Ball){
ballHitSomething((Ball) fb.getBody().getUserData(),fa);
}
if(fa.getBody().getUserData() instanceof Bomb){
bombHitSomething((Bomb) fa.getBody().getUserData(),fb);
}else if(fb.getBody().getUserData() instanceof Bomb){
bombHitSomething((Bomb) fb.getBody().getUserData(),fa);
}
if(fa.getBody().getUserData() instanceof LocalEffectEntity){
if(fa.isSensor()){
inLocalEffectRange((LocalEffectEntity) fa.getBody().getUserData(),fb);
}else{
objectInVoid(fb);
}
}else if(fb.getBody().getUserData() instanceof LocalEffectEntity){
if(fb.isSensor()){
inLocalEffectRange((LocalEffectEntity) fb.getBody().getUserData(),fa);
}else{
objectInVoid(fa);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.