我一直在处理CCPhysicsSprite类中的联系人,因为我主要将userdata设置为CCPhysicsSprite。如下:
ContactListenerClass.mm:
void ContactListenerClass:: BeginContact(b2Contact *contact){
b2Fixture *fixtureA = contact->GetFixtureA();
b2Fixture *fixtureB = contact->GetFixtureB();
b2Body *fixtureABody = fixtureA->GetBody();
b2Body *fixtureBBody = fixtureB->GetBody();
CCPhysicsSprite* physicsSprite = (CCPhysicsSprite*)fixtureABody->GetUserData();
CCPhysicsSprite* physicsSprite2 = (CCPhysicsSprite*)fixtureBBody->GetUserData();
[physicsSprite spritesHadContact:physicsSprite2];
}
spritesHadContact方法在CCPhysicsSprite.mm类中:
-(void)spritesHadContact:(CCPhysicsSprite*)secondPhysicsSprite {
int tag1 = self.tag;
int tag2 = secondPhysicsSprite.tag;
if ((tag1 == 30) && (tag2 == 40 )) || ((tag1 == 40) && (tag2 == 30)) {
CCLOG(@"proceed to handle contact");
}
上面的例子有点直截了当。但是当我开始创建和销毁关节时,我意识到除了处理联系人的CCPhysicsSprite之外还有一个类更好。我做了一个类(contactHandler)来做那个,但它不起作用。我不知道我做错了什么。请参阅以下内容:
ContactHandler.h:
#import "CCPhysicsSprite.h"
@interface ContactHandler : CCPhysicsSprite {
}
-(void)spritesHadContact:(CCPhysicsSprite*)firstPhysicsSprite otherSprite:(CCPhysicsSprite*)secondPhysicsSprite;
@end
ContactHandler.mm:
#import "ContactHandler.h"
@implementation ContactHandler
-(void)spritesHadContact:(CCPhysicsSprite*)firstPhysicsSprite otherSprite:(CCPhysicsSprite*)secondPhysicsSprite {
int tag1 = firstPhysicsSprite.tag;
int tag2 = secondPhysicsSprite.tag;
if ((tag1 == 30) && (tag2 == 40 )) || ((tag1 == 40) && (tag2 == 30)) {
CCLOG(@"proceed to handle contact");
}
@end
ContactListenerClass.h:
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "Box2D.h"
#import "ContactHandler.h"
class ContactListenerClass : public b2ContactListener {
public:
ContactHandler* contactHandler;
void BeginContact(b2Contact* contact);
};
ContactListenerClass.mm:
#import "ContactListenerClass.h"
#import "HelloWorldLayer.h"
void ContactListenerClass:: BeginContact(b2Contact *contact)
{
b2Fixture *fixtureA = contact->GetFixtureA();
b2Fixture *fixtureB = contact->GetFixtureB();
b2Body *fixtureABody = fixtureA->GetBody();
b2Body *fixtureBBody = fixtureB->GetBody();
CCPhysicsSprite* physicsSprite = (CCPhysicsSprite*)fixtureABody->GetUserData();
CCPhysicsSprite* physicsSprite2 = (CCPhysicsSprite*)fixtureBBody->GetUserData();
[contactHandler spritesHadContact:physicsSprite otherSprite:physicsSprite2];
}
已更新
ContactHandler类中的spritesHadContact方法不会将CCLOG打印到控制台。我尝试了一个CCLOG来查看正在进行的联系,但该方法无法识别任何联系人。