2

我的联系人监听器代码中出现 EXC_BAD_ACCESS 错误。下面是代码:

主对象类(GameObjects),所有对象都通过它进行子类化:

游戏对象.h:

#import "cocos2d.h"
#import "CCNode.h"
#import "CCPhysicsSprite.h"
#import "Box2D.h"
#include <math.h>

@interface GameObjects : CCNode {
    //b2Body* objectBody_;
}

-(b2Body*)getObjectBody;
-(void)objectsTouched:(GameObjects*)otherObject;
@end

GameObjects.mm(现在我只想告诉 CCLOG 是否有效):

#import "GameObjects.h"

@implementation GameObjects

-(b2Body*)getObjectBody    {
}

-(void)objectsTouched:(GameObjects*)otherObject   {
   CCLOG(@"it's working");
}

@end

ContactListenerTest.h:

#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "Box2D.h"
#import "Enemy.h"
#import "Sprite.h"
#import "GameObjects.h"



class ContactListenerTest : public b2ContactListener    {
public:

   b2World* world;
   void BeginContact(b2Contact* contact);
};

ContactListenerTest.mm:

#import "ContactListenerTest.h"

void ContactListenerTest:: BeginContact(b2Contact *contact)
{

    b2Fixture       *fixtureA = contact->GetFixtureA();
    b2Fixture       *fixtureB = contact->GetFixtureB();
    b2Body          *fixtureABody = fixtureA->GetBody();
    b2Body          *fixtureBBody = fixtureB->GetBody();

    GameObjects* spriteObject = (GameObjects*)fixtureABody->GetUserData();
    GameObjects* spriteObject2 = (GameObjects*)fixtureBBody->GetUserData();

    [spriteObject objectsTouched:spriteObject2];
    [spriteObject2 objectsTouched:spriteObject];

}

当我收到 EXC_BAD_ACCESS 错误时,控制台中会打印以下内容:

-[Enemy objectsTouched:]: unrecognized selector sent to instance 0x8558840

Enemy 是 GameObjects 的子类之一。

4

2 回答 2

1

验证 userdata 对象实际上是 GameObjects 类:

NSAssert1([spriteObject isKindOfClass:[GameObjects class]], 
          @"userdata %@ not a game object", spriteObject);
NSAssert1([spriteObject2 isKindOfClass:[GameObjects class]], 
          @"userdata 2 %@ not a game object", spriteObject2);
于 2013-05-08T21:15:25.867 回答
0

当你初始化 GameObject 时,你应该确保创建的 body 的 UserData 指向你的 GameObject。像这样的东西:

objectBody_->SetUserData(self);
于 2013-05-09T09:39:18.787 回答