第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());
}
}
本文介绍两种在Box2D物理引擎中同步精灵位置及旋转,并根据需要移除对应身体的方法。第一种方法适用于需要从列表中删除身体的情况,使用while循环遍历;第二种方法则适用于不需要删除的情况,采用for循环进行遍历。
144

被折叠的 条评论
为什么被折叠?



