为什么精灵不赋给刚体的userdata属性也能与其绑定

在cocos2d-2.0-x-2.04 版本中,创建一个box2d工程,其中的默认代码中,定义了一个PhysicsSprite类,按道理精灵与刚体绑定的时候需要将精灵的指针赋给刚体的userdata属性,他们才能关联起来,但是模板代码中并没有这么做,而是刚体赋给精灵的一个属性,但是照样工作正常,我很疑惑,希望大侠指点啊

下面是添加精灵的方法,我很纳闷不知道怎么绑定的求解

void HelloWorld::addNewSpriteAtPosition(CCPoint p)
{
CCLOG(“Add sprite %0.2f x %02.f”,p.x,p.y);
CCNode* parent = getChildByTag(kTagParentNode);

//We have a 64x64 sprite sheet with 4 different 32x32 images.  The following code is
//just randomly picking one of the images
//int idx = (CCRANDOM_0_1() > .5 ? 0:1);
//int idy = (CCRANDOM_0_1() > .5 ? 0:1);
PhysicsSprite *sprite = new PhysicsSprite();
sprite->initWithTexture(m_pSpriteTexture, CCRectMake(0,0,128,128));
sprite->autorelease();

parent->addChild(sprite);

sprite->setPosition( CCPointMake( p.x, p.y) );

// Define the dynamic body.
//Set up a 1m squared box in the physics world
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);

b2Body *body = world->CreateBody(&bodyDef);

// Define another box shape for our dynamic body.
//b2PolygonShape dynamicBox;
//dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box

b2CircleShape circle;
circle.m_radius =64.0/PTM_RATIO;

// Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &circle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
fixtureDef.restitution=0.8f;
body->CreateFixture(&fixtureDef);

sprite->setPhysicsBody(body);

}

没注意还有这种方式,,你看得很细心啊,:smiley:

— Begin quote from ____

zack 发表于 2013-1-4 09:23 url

body和sprite贴图相同大小和位置相同就行了,如果body移动的话,相关联的sprite如何移动?那就在userdata中 …

— End quote

谢谢你的回答,我发现示例中的Sprite派生类PhysicsSprite重写了父类的两个方法,一个是
bool PhysicsSprite::isDirty(void)
{
return true;
}
还有 一个就是
nodeToParentTransform

那么isDirty一直返回的true的意识就是每个轮回,这个sprite都要重新绘制,那么重的话,就每次都回调用nodeToParentTransform这个方法,示例代码在nodeToParentTransform方法中更具刚体的位置,适当修改精灵的位置,所以update方法中方法没有用到,userdata中的数据永远是null,

body和sprite贴图相同大小和位置相同就行了,如果body移动的话,相关联的sprite如何移动?那就在userdata中保存sprite指针,同步更新sprite位置。

没注意还有这种方式,,你看得很细心啊,:smiley:

body和sprite贴图相同大小和位置相同就行了,如果body移动的话,相关联的sprite如何移动?那就在userdata中保存sprite指针,同步更新sprite位置。