方法:
-(vector<b2PolygonShape>*) parsePolyArrStr:(NSString*)polyArrStr {
if(polyArrStr == nil || [polyArrStr isEqualToString:@""]) {
NSLog(@"shapeArrStr: nil or \"\"");
return nil;
}
vector<b2PolygonShape> *target = new vector<b2PolygonShape>();
NSArray *childShapes = [polyArrStr componentsSeparatedByString:@"z"];
for(uint i = 0; i < [childShapes count]; ++ i) {
NSString *polyStr = [childShapes objectAtIndex:i];
b2PolygonShape polyShape = [self parsePolyStr:polyStr];
target->push_back(polyShape);
}
return target;
}
用例:
-(void) addBear {
NSString *bearStr = @"0.625v0.53125,0.15625v1.03125,-0.40625v0.90625,-0.625v0.34375,0.34375v0.1875z0.34375v0.1875,-0.625v0.34375,-0.46875v-0.71875,-0.09375v-1.03125,0.34375v-0.96875,0.625v-0.40625";
StringParser *sp = [StringParser parser];
vector<b2PolygonShape> *v = [sp parsePolyArrStr:bearStr];
b2Vec2 po = b2Vec2(5.0f, 7.0f);
b2BodyDef bd;
bd.position = po;
bd.type = b2_dynamicBody;
b2Body *body = _world->CreateBody(&bd);
body->m_isCuttable = false;
body->SetFixedRotation(true);
b2FixtureDef fd;
fd.density = 1.0f;
fd.friction = 0.5f;
fd.restitution = 0.5f;
for(uint i = 0; i < v->size(); ++ i) {
fd.shape = &(v->at(i));
body->CreateFixture(&fd);
}
// 熊的 sprite 不放到任何 batch 里面,因为只有一个,而且熊的动画很多,到时候很有可能会用上第二张,第三张纹理图片~
CCSprite *sBear = [CCSprite spriteWithSpriteFrameName:@"animBear0.png"];
[sBear setPosition:ccp(po.x * PTM_RATIO, po.y * PTM_RATIO)];
// release->debug 揪出的第一个bug(release模式下重复添加并不会出错)~
// [_gameLayer addChild:sBear];
// [_single spriteRunRepeatAction:sBear animName:ANIMATION_CACHE_BEAR_WALK];
CCAnimation *walkAnim = [[CCAnimationCache sharedAnimationCache] animationByName:ANIMATION_CACHE_BEAR_WALK];
CCAnimate *walk = [CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO];
CCAnimation *turnAnim = [[CCAnimationCache sharedAnimationCache] animationByName:ANIMATION_CACHE_BEAR_TURN];
CCAnimate *turn = [CCAnimate actionWithAnimation:turnAnim restoreOriginalFrame:NO];
CCAnimation *attackAnim = [[CCAnimationCache sharedAnimationCache] animationByName:ANIMATION_CACHE_BEAR_ATTACK];
CCAnimate *attack = [CCAnimate actionWithAnimation:attackAnim restoreOriginalFrame:NO];
CCSequence *sequence = [CCSequence actions:walk, turn, attack, nil];
CCRepeatForever *repeatAction = [CCRepeatForever actionWithAction:sequence];
[sBear runAction:repeatAction];
body->SetUserData(sBear);
[_gameLayer addChild:sBear z:-8];
}