Skip to content

Instantly share code, notes, and snippets.

@tomvangreen
Created June 8, 2014 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomvangreen/04b8d13941b9e5c3bd0f to your computer and use it in GitHub Desktop.
Save tomvangreen/04b8d13941b9e5c3bd0f to your computer and use it in GitHub Desktop.
My contact listener implementation
package ch.digitalmeat.meatpong;
import ch.digitalmeat.meatpong.event.Events;
import ch.digitalmeat.meatpong.event.NotificationType;
import ch.digitalmeat.meatpong.game.Entity;
import ch.digitalmeat.meatpong.game.EntityType;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Manifold;
public class ContactListenerImpl implements ContactListener {
private final Events events;
public ContactListenerImpl(Events events) {
this.events = events;
}
@Override
public void beginContact(Contact contact) {
Body a = contact.getFixtureA().getBody();
Body b = contact.getFixtureB().getBody();
if (!handleBeginContact(contact, a, b)) {
handleBeginContact(contact, b, a);
}
}
private boolean handleBeginContact(Contact contact, Body a, Body b) {
if (isOfType(a, EntityType.Destructor) && isOfType(b, EntityType.Ball)) {
events.destroyed(b, a);
events.notification(NotificationType.BallLost);
return true;
} else if (isOfType(a, EntityType.Paddle) && isOfType(b, EntityType.Ball)) {
events.paddleHit(a, b);
events.notification(NotificationType.PaddleHit);
return true;
} else if (isOfType(a, EntityType.Wall) && isOfType(b, EntityType.Ball)) {
events.notification(NotificationType.WallHit);
return true;
} else if (isOfType(a, EntityType.Enemy) && isOfType(b, EntityType.Ball)) {
events.enemyHit(a, b);
events.notification(NotificationType.EnemyHit);
return true;
}
return false;
}
public boolean isOfType(Body body, EntityType type) {
Object userData = body.getUserData();
if (userData instanceof EntityType) {
EntityType bodyType = (EntityType) userData;
return bodyType.equals(type);
} else if (userData instanceof Entity) {
Entity entity = (Entity) userData;
return entity.type.equals(type);
}
return false;
}
@Override
public void endContact(Contact contact) {
}
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment