0

一直以来,我一直在处理 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),但它不工作。我不知道我做错了什么。请看下面:

联系人处理程序.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 来查看发生了哪些联系人,但该方法无法识别任何联系人。

4

0 回答 0