A pair of newbie questions

Hey guys, first of all sorry for making these basic questions. I'm making a 2d game and I wanted to understand how things work.

First of all the character controlled by the player needs to push a box when he collides with it. Does the box have to be a dynamic or static entity? I guess dynamic.

Secondly there will be entities that will hurt the player on collision (kinematic / static like traps and dynamic enemies). How do I check if there is a collision between two entities so that I can lower the hit points of the player?

thanks a lot!
1) Yes you have to create dynamic body if you want some interaction.

2) The simplest way is to use a contact listener. Create a custom class that implements ContactListener:

Code: Select all

public class MyContactListener implements ContactListener {

    public class ContactInfo {
        public Fixture fixture;
        public float damage;
    }
    public ArrayList<ContactInfo> contacts = new ArrayList<>();

    @Override
    public void beginContact(Contact cntct) {
        // Do nothing
    }

    @Override
    public void endContact(Contact cntct) {
        // Do nothing
    }

    @Override
    public void preSolve(Contact cntct, Manifold mnfld) {
        // Do nothing
    }

    @Override
    public void postSolve(Contact cntct, ContactImpulse ci) {

        int count = cntct.getManifold().pointCount;
        float maxImpulse = 0.0f;
        for (int i = 0; i < count; i++) {
            maxImpulse = Math.max(maxImpulse, ci.normalImpulses[i]);
        }

        if (cntct.m_fixtureA.getBody().getUserData() instanceof YourPlayerBody) {

            ContactInfo contact = new ContactInfo();
            contact.fixture = cntct.m_fixtureA;
            contact.damage = maxImpulse;           
            contacts.add(contact);
        }

        if (cntct.m_fixtureB.getBody().getUserData() instanceof YourPlayerBody) {

            ContactInfo contact = new ContactInfo();
            contact.fixture = cntct.m_fixtureB;
            contact.damage = maxImpulse;         
            contacts.add(contact);
        }


    }
}


Then use it with your world object through the setContactListener() function. If you look closely I add all contacts to an array list because you might want to perform some change to the bodies on contact but it is not allowed while being in a simulation step. That's it, you call your world.step() function and check if your contacts array contains something.

I also calculate the damage based on manifold points, this mean: more energy = more damage 🙂

Original thread: https://box2d.org/forum/viewtopic.php?t=9468