对于不规则的精灵我们可以借助PhysicsEditor来制作shape ,
对于地图可以使用Tiled软件制作瓷砖地图。
今天主要记录一下如何把CCSprite与不规则刚体进行绑定,然后一起移动
//初始化玩家
1.加载shape文件,在init方法中添加:
//加载shape文件
[[GB2ShapeCache sharedShapeCache] addShapesWithFile:@"physicShape.plist"];
.plist文件内容大体如下:
metadata
format
1
ptm_ratio
32
bodies
Player1
anchorpoint
{ 0.0000,0.0000 }
fixtures
density 2
friction 0
restitution 0
filter_categoryBits 1
filter_groupIndex 0
filter_maskBits 65535
isSensor
id
fixture_type POLYGON
polygons
{ 1.000,0.000 }
{ 32.000,0.000 }
{ 27.000,32.000 }
{ 7.000,32.000 }
RetroCoin
anchorpoint
{ 0.0000,0.0000 }
fixtures
density 2
friction 0
restitution 0
filter_categoryBits 1
filter_groupIndex 0
filter_maskBits 65535
isSensor
id
fixture_type POLYGON
polygons
{ 4.000,3.000 }
{ 17.000,0.000 }
{ 28.000,3.000 }
{ 28.000,28.000 }
{ 16.000,32.000 }
{ 4.000,28.000 }
2.初始化精灵和刚体及夹具
#pragma mark 初始化玩家
-(void)initPlayer{
//创建对象层 获得对象的产生点
CCTMXObjectGroup *objects=[_gameMap objectGroupNamed:@"objects"];
NSMutableDictionary *spawnPoint=[objects objectNamed:@"StartPoint"];
//获得出生点坐标
float x=[[spawnPoint valueForKey:@"x"] floatValue];
float y=[[spawnPoint valueForKey:@"y"] floatValue];
_player=[CCSprite spriteWithFile:@"Player1.png"];
_player.position=ccp(x,y);
_player.anchorPoint=CGPointZero; //设置描点为0,0 否则与刚体不能重合
b2BodyDef playerBodyDef; //定义刚体结构体的定义
[self addChild:_player];
playerBodyDef.type=b2_dynamicBody;
playerBodyDef.fixedRotation=true; //不会旋转
playerBodyDef.position.Set(x/PTM_RATIO, y/PTM_RATIO);
_playBody=world->CreateBody(&playerBodyDef);
_playBody->SetUserData(_player);
[[GB2ShapeCache sharedShapeCache] addFixturesToBody:_playBody forShapeName:@"Player1"]; //为刚体设置夹具
}
3.在update函数中添加更新位置方法
for(b2Body *b = world->GetBodyList(); b; b=b->GetNext()) {
if (b->GetUserData() != NULL) {
CCSprite *sprite = (CCSprite *)b->GetUserData(); //获得精灵对象
if (sprite != nil) {
b2Vec2 bodyPos = b->GetPosition(); //获得刚体的位置
CGPoint pos = CGPointMake(bodyPos.x * PTM_RATIO, bodyPos.y * PTM_RATIO); //变换为坐标
float32 rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
sprite.position = pos;
sprite.rotation = rotation;
}
}
}
效果图:
转载请注明:版权所有http://1.wildcat.sinaapp.com/