2010-02-25 94 views
1

基本上我有2個多邊形爲我的身體。當我爲userData添加一個精靈時,紋理的位置不在我想要的位置。我想要做的是調整體內紋理的位置。這裏是我設置的地方的代碼示例:如何在box2d body中設置精靈的位置?

CCSpriteSheet *sheet = (CCSpriteSheet*) [self getChildByTag:kTagSpriteSheet]; 
CCSprite *pigeonSprite = [CCSprite spriteWithSpriteSheet:sheet rect:CGRectMake(0,0,40,32)]; 
[sheet addChild:pigeonSprite z:0 tag:kPigeonSprite]; 

pigeonSprite.position = ccp(p.x, p.y); 

bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO); 
bodyDef.userData = sprite; 
b2Body *body = world->CreateBody(&bodyDef); 

b2CircleShape dynamicCircle; 
dynamicCircle.m_radius = .25f; 
dynamicCircle.m_p.Set(0.0f, 1.0f); 

     // Define the dynamic body fixture. 
b2FixtureDef circleDef; 
circleDef.shape = &dynamicCircle; 
circleDef.density = 1.0f; 
circleDef.friction = 0.3f; 

body->CreateFixture(&circleDef); 

b2Vec2 vertices[3]; 
vertices[0].Set(-0.5f, 0.0f); 
vertices[1].Set(0.5f, 0.0f); 
vertices[2].Set(0.0f, 1.0f); 
b2PolygonShape triangle; 
triangle.Set(vertices, 3); 

b2FixtureDef triangleDef1; 
triangleDef1.shape = ▵ 
triangleDef1.density = 1.0f; 
triangleDef1.friction = 0.3f; 

body->CreateFixture(&triangleDef1); 
+0

我可以建議嘗試從代碼片段中刪除所有不必要的東西嗎?例如,密度和摩擦與精靈定位幾乎沒有任何關係。就我而言,我不願意通過一大塊代碼來回答一個簡單的問題。另一方面,如果您不確定某件事情是否不會影響您的問題,那麼最好不要讓它出現。但請儘量降低到最低程度。 – Felixyz 2010-03-20 19:23:59

回答

2

我不熟悉objective-c,但我會試一試。

我能看到的全部是你正在存儲一個指向體內用戶數據中的精靈對象的指針,然後將它留在那裏。如果你希望身體的位置被轉移到精靈,你需要每一幀更新它。

在C++中,這看起來像這樣。

// To be called each time physics should be updated. 
void physicsStep(float32 timeStep, int32 velocityIterations, int32 positionIterations) { 
    // This is the usual update routine. 
    world.Step(timeStep, velocityIterations, positionIterations); 
    world.ClearForces(); 

    // SpriteClass can be replaced with any class you favor. 
    // Assume there is a known pointer to the b2Body. Otherwise you'll have to get that, 
    // or iterate over all bodies in the world. 
    SpriteClass *sprite = (SpriteClass*)body->GetUserData(); 

    // Once you have the pointer you can transfer all the data. 
    sprite.position = body->GetPosition(); 
    sprite.angle = body->GetAngle(); 
    // ... and so on 
} 

用戶數據只是b2Body中的一個任意存儲空間,而Box2D不知道您決定在那裏存儲什麼。

0

要與身體移動精靈,然後你必須設置精靈位置的更新方法

像這樣的Cocos2D-X 這裏

sprite = static_cast<CCSprite*>body->GetUserData(); 
sprite->setPosition(vec2(body->GetPosition().x*PTM_RATIO, body->GetPosition().y*PTM_RATIO)); 
sprite->setRotation(-CC_Radian_to_Degree(body->GetAngle)); 
accotring身體

PTM_RATIO = 32;