0

我试图在释放移动精灵的鼠标关节时获取精灵的确切位置(即使精灵可能仍在移动)并显示它。我正在使用 Cocos2d 和 Box2d。下面是代码 ccTouchesEnded 方法。

ccTouchesEnd:

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{

if (mouseJoint)
{
    b2Fixture *fixture;
    CCSprite *mySprite = (CCSprite *) fixture->GetUserData();
    NSInteger attachedSprite = mySprite.tag;
    if (attachedSprite == 1) {
        CGPoint spritePosition = mySprite.position;

        CCLOG(@"the sprite position is x:%0.2f, y:%0.2f", spritePosition.x, spritePosition.y);
        }
    world->DestroyJoint(mouseJoint);
    mouseJoint = NULL;
}
}

我不断收到指向该行的 EXC_BAD_ACCESS 错误:

CCSprite *mySprite = (CCSprite *) fixture->GetUserData();

我不太确定出了什么问题。请帮忙。

4

1 回答 1

1

您收到该错误是因为夹具尚未初始化,请查看本 教程,了解他如何遍历所有世界元素

for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {
    if (b->GetUserData() != NULL) {
        CCSprite *curSprite = (CCSprite *)b->GetUserData();
...
    }
}

在执行 GetUserData() 之前,您必须为夹具分配一些东西

于 2012-08-08T20:59:03.877 回答