Need to know when collision is begin and end box2d

懵懂的女人 提交于 2019-12-11 17:08:51

问题


public class Contact 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--; }


来源:https://stackoverflow.com/questions/50927510/need-to-know-when-collision-is-begin-and-end-box2d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!