void HelloWorld::addNewSpriteAtPosition(Vec2 p) { log("Add sprite %0.2f x %02.f",p.x,p.y); //创建物理引擎精灵对象A auto spriteA = Sprite::create("BoxA2.png"); ① spriteA->setPosition(p); this->addChild(spriteA); // 动态物体A定义 b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO); b2Body *bodyA = world->CreateBody(&bodyDef); bodyA->SetUserData(spriteA); ② //创建物理引擎精灵对象B auto spriteB = Sprite::create("BoxB2.png"); ③ spriteB->setPosition(p + Vec2(100, -100)); ④ this->addChild(spriteB); // 动态物体B定义 bodyDef.type = b2_dynamicBody; Vec2 posB = spriteB->getPosition(); bodyDef.position.Set(posB.x/PTM_RATIO , posB.y /PTM_RATIO); ⑤ b2Body *bodyB = world->CreateBody(&bodyDef); bodyB->SetUserData(spriteB); ⑥ // 定义2米见方的盒子形状 b2PolygonShape dynamicBox; dynamicBox.SetAsBox(1, 1); // 动态物体夹具定义 b2FixtureDef fixtureDef; //设置夹具的形状 fixtureDef.shape = &dynamicBox; //设置密度 fixtureDef.density = 1.0f; //设置摩擦系数 fixtureDef.friction = 0.3f; //使用夹具固定形状到物体上 bodyA->CreateFixture(&fixtureDef); ⑦ bodyB->CreateFixture(&fixtureDef); ⑧ // 距离关节定义 b2DistanceJointDef jointDef; ⑨ jointDef.Initialize(bodyA, bodyB, bodyA->GetWorldCenter(), bodyB->GetWorldCenter()); ⑩ jointDef.collideConnected = true; ⑪ bodyA->GetWorld()->CreateJoint(&jointDef); ⑫ }
这些关节定义初始化的时候参数都各不相同,但是参数都是比较类似的。此外,除了上面列出的关节外,还有一些其它的关节,这关节不是很常用,这里不再一一介绍了。
《Cocos2d-x实战 C++卷》现已上线,各大商店均已开售:
京东:http://item.jd.com/11584534.html
亚马逊:http://www.amazon.cn/Cocos2d-x%E5%AE%9E%E6%88%98-C-%E5%8D%B7-%E5%85%B3%E4%B8%9C%E5%8D%87/dp/B00PTYWTLU
当当:http://product.dangdang.com/23606265.html
互动出版网:http://product.china-pub.com/3770734
《Cocos2d-x实战 C++卷》源码及样章下载地址:
源码下载地址:http://51work6.com/forum.php?mod=viewthread&tid=1155&extra=page%3D1
样章下载地址:http://51work6.com/forum.php?mod=viewthread&tid=1157&extra=page%3D1