I am trying to implement this solution to my problem from this answer: libGDX Box2D: How to destroy body after collision? But nothing is happening but the method executes and shows no errors. This means that the kugelbody (circle) is not inserted into the array list. (I think)
I need the circlebody to be deleted on collision with a square. The square is saved in an arraylist with other squares.
world.setContactListener(new ContactListener() {
@Override
public void beginContact(Contact contact) {
Fixture fixtureA = contact.getFixtureA();
Fixture fixtureB = contact.getFixtureB();
//ist a oder b ein quadrat?
boolean isSquareA = fixtureA != null && squareBodies.contains(fixtureA.getBody());
boolean isSquareB = fixtureB != null && squareBodies.contains(fixtureB.getBody());
if (isSquareA || isSquareB) {
// Kollision mit einem Quadrat
Body ballBody = isSquareA ? fixtureB.getBody() : fixtureA.getBody();
int squareIndex = isSquareA ? squareBodies.indexOf(fixtureA.getBody()) : squareBodies.indexOf(fixtureB.getBody());
// Todo kontostandplus einsatz * multipklikrator
//todo evtl 0.2 | 0.5 |1.2 |2 |10 |2 |1.2 |0.5 |0.2
long []abc = {(long) 0.2, (long) 0.5, (long) 1.2,2,10};
switch (squareIndex) {
(...) }
delkugel.add(ballBody);
}
}
The render method:
public void render() {
Gdx.gl20.glClearColor(0, 0, 0, 1);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
b2dr.render(world, b2dcam.combined);
if (delkugel.size() > 0) { delkugel.clear();}
stage.act();
stage.draw();
}
The method of the Ballgeneration:
private void dropBall(int posX){
final BodyDef bdef = new BodyDef();
FixtureDef fdef = new FixtureDef();
bdef.position.set(posX / PPM, 790 / PPM);
bdef.type = BodyDef.BodyType.DynamicBody;
// Randomly drop ball
final Body body = world.createBody(bdef);
CircleShape cshape = new CircleShape();
cshape.setRadius(13 / PPM);
fdef.shape = cshape;
fdef.filter.categoryBits = Box2dVars.BIT_BALL;
fdef.filter.maskBits = Box2dVars.BIT_WALLS | Box2dVars.BIT_PEG;
fdef.restitution = 0.7f;
fdef.density = 0.9f;
fdef.friction = 0.1f;
body.createFixture(fdef).setUserData("ball");
Timer.schedule(new Timer.Task() {
@Override
public void run() {
if (body != null && world != null && world.getBodyCount() > 0) {
world.destroyBody(body);
}
}
}, 10);
}
And the method of the squaregeneration:
int squareSize = 20;
for (int i = 10; i < 100; i = i + 10) {
BodyDef bdef;
FixtureDef fdef;
PolygonShape shape;
bdef = new BodyDef();
fdef = new FixtureDef();
shape = new PolygonShape();
bdef.position.set((Game.WIDTH * i / PPM) / PPM, (150 + 10) / PPM);
bdef.type = BodyDef.BodyType.StaticBody;
Body body = world.createBody(bdef);
shape.setAsBox(squareSize / PPM, squareSize / PPM);
fdef.shape = shape;
fdef.filter.categoryBits = Box2dVars.BIT_WALLS;
fdef.filter.maskBits = Box2dVars.BIT_BALL;
body.createFixture(fdef).setUserData("wall");
squareBodies.add(body);
}
}