need to know when collision is begin and end box2d

2019-08-18 00:26发布

问题:

 public class Conntact implements ContactListener {


    @Override
    public void beginContact(Contact contact) {
        Fixture fa = contact.getFixtureA();
        Fixture fb = contact.getFixtureB();
        if (fa.getFilterData().categoryBits==16){

            ((Gamescreen)fa.getUserData()).starttouch(fa,fb);
        }
 @Override
    public void endContact(Contact contact) {
        Fixture fa = contact.getFixtureA();
        Fixture fb = contact.getFixtureB();
        if (fa.getFilterData().categoryBits==16)
        {
            ((Gamescreen)fa.getUserData()).endtouch();
        }

this code works fine when there is just one object to touch but some time i need to make like tow object beside of each others. like when the player walk on 2 objects (without jumping) beside each others the second method (endcontact) called but the first method (begincontact) does not get call again.

回答1:

If I understood correctly, then this link may be what you're looking for: http://www.iforce2d.net/b2dtut/collision-callbacks

It's C++, but you can see example implementation of collision callback for a pair of objects:

void BeginContact(b2Contact* contact) {

  //check if fixture A was a ball
  void* bodyUserData = contact->GetFixtureA()->GetBody()->GetUserData();
  if ( bodyUserData )
    static_cast<Ball*>( bodyUserData )->startContact();

  //check if fixture B was a ball
  bodyUserData = contact->GetFixtureB()->GetBody()->GetUserData();
  if ( bodyUserData )
    static_cast<Ball*>( bodyUserData )->startContact();

}

Additionally, you don't save true/false if contact started, but number of contacts:

//new implementation for contact state change
void startContact() { m_numContacts++; }
void endContact() { m_numContacts--; }