第1种方法,在对 body 列表有删除操作的时候,
采用 while 的遍历方式比较方便(详见box2d白皮书)~
/** Iterate over the bodies in the physics world */
b2Body *node = _world->GetBodyList();
while(node) {
b2Body *b = node;
node = node->GetNext();
if(b->GetUserData() != NULL) {
//Synchronize the AtlasSprites position and rotation with the corresponding(相应的) body
CCSprite *myActor = (CCSprite*)b->GetUserData();
CGPoint position = CGPointMake(b->GetPosition().x*PTM_RATIO, b->GetPosition().y*PTM_RATIO);
if(![MGameScene isPositionOutOfBounds:position]) { //如果没有越界的话,实时更新~
myActor.position = position;
myActor.rotation = -1 *CC_RADIANS_TO_DEGREES(b->GetAngle());
} else {
[_single.gameLayerremoveChild:myActor cleanup:YES];
b->SetUserData(NULL);
b->SetTransform(b2Vec2(7.5f,20.0f), 0.0f); // 设置一个合理的位置储存这些用处已经不大的body们~
b->SetType(b2_staticBody);
}
}
}
第2种方法,适用于不对 body 列表作删除操作的情况
for (b2Body* b =_world->GetBodyList(); b; b = b->GetNext()) {
if (b->GetUserData() !=NULL) {
//Synchronize the AtlasSprites position and rotation with the corresponding body
CCSprite *myActor = (CCSprite*)b->GetUserData();
myActor.position =CGPointMake( b->GetPosition().x *PTM_RATIO, b->GetPosition().y *PTM_RATIO);
myActor.rotation = -1 *CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}