问题
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