0
\$\begingroup\$

I am trying to hold the contacts made during a collision in an array list. After I add n amount of contacts, when I try to retrieve them later on, they point to the last contact made in the world.

How can I save the contact that was there initially?

I am using Box2d and Libgdx with Java.

public void beginContact(Contact contact) {
    Fixture fa = contact.getFixtureA();
    Fixture fb = contact.getFixtureB();

    if (isFixtureCheckpoint(fa) || isFixtureCheckpoint(fb)) {
        checkpointContact.add(contact);
    }
}

and when I am trying to retrieve in the update method, any contact that i get back is from the last contact made in the world:

public void update(float delta) {
    Fixture fa;
    Fixture fb;

    if (checkpointContact.size > 0) {
        fa = checkpointContact.first().getFixtureA();
        fb = checkpointContact.first().getFixtureB();

        if (isAnyFixtureRearWheel(fa, fb)) {
            // <--- This returns true. Why?
        }

        if (isFixtureCheckpoint(fa)) {
            context.progressHandler.checkpointPassed(fa.getBody().getWorldCenter());
        }
        if (isFixtureCheckpoint(fb)) {
            context.progressHandler.checkpointPassed(fb.getBody().getWorldCenter());
        }
    }
}

The comparison functions are comparing to different unrelated classes:

/* Check if ANY fixture is a rear wheel */
private boolean isAnyFixtureRearWheel(Fixture fa, Fixture fb) {
    if (((fa.getUserData() instanceof VehicleRearWheel) || (fb.getUserData() instanceof VehicleRearWheel))) {
            return true;
    }
    return false;
}

/* Check if fixture is contacting the flag */
private boolean isFixtureCheckpoint(Fixture f) {
    return f.getUserData() instanceof ProgressHandler;
}

EDIT: Last time I checked Java was considered a pass by value language?

\$\endgroup\$
  • \$\begingroup\$ It is impossible to create a new Contact because Box2d has the constructor set to protected. And I was adding them as is to an array list. \$\endgroup\$ – Danny Watts Sep 13 '15 at 2:29
  • \$\begingroup\$ This is what I ended up doing in the end :) Give that as an answer and I will accept it. Thank you. \$\endgroup\$ – Danny Watts Sep 13 '15 at 3:28
0
\$\begingroup\$

It seems like Box2D is not creating a new instance of Contact everytime, but instead it is changing the most recent contact object's variables. So when you reference the contact object, you get the "updated" one (same object, but with updated variables).

You could simply save whatever information you need from the contact object to an object of your own custom class and add that to your list instead.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.