這個實例的運行後的場景如圖所示,當場景啓動後,玩家能夠觸摸點擊屏幕,每次觸摸時候,就會在觸摸點和附近生成兩個新的精靈,它們的運行是自由落體運動,它們之間的距離是固定的。圖示是開啓了繪製調試遮罩,從圖中可見,調試遮罩不只會顯示物體,還會顯示關節。html
使用距離關節實例web
使用距離關節實例(繪製調試遮罩)微信
代碼部分中HelloWorldScene.h文件與上一節的實例很是相似,再也不介紹了。HelloWorldScene.cpp中建立物理世界和指定世界的邊界語句是在HelloWorld::createScene()和HelloWorld::init()函數中,這兩個函數相似於上一節實例,這裏也再也不解釋這些函數代碼了。app
HelloWorldScene.cpp中與使用關節的相關代碼以下:函數
[html] view plaincopyoop
<EMBED id=ZeroClipboardMovie_1 height=18 name=ZeroClipboardMovie_1 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=1&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">網站
bool HelloWorld::onTouchBegan(Touch* touch, Event* event) this
{ spa
Vec2 location = touch->getLocation(); .net
addNewSpriteAtPosition(location);
return false;
}
void HelloWorld::addNewSpriteAtPosition(Vec2 p)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto boxA = Sprite::create("BoxA2.png"); ①
boxA->setPosition(origin+ p); ②
auto boxABody = PhysicsBody::createBox(boxA->getContentSize()); ③
boxA->setPhysicsBody(boxABody); ④
addChild(boxA, 10, 100); ⑤
auto boxB = Sprite::create("BoxB2.png");
boxB->setPosition(origin + p + Vec2(0, -120));
auto boxBBody = PhysicsBody::createBox(boxB->getContentSize());
boxB->setPhysicsBody(boxBBody);
addChild(boxB, 20, 101);
auto world = this->getScene()->getPhysicsWorld(); ⑥
PhysicsJointDistance* joint = PhysicsJointDistance::construct(boxABody, boxBBody,
Vec2(0, 0), Vec2(0, boxB->getContentSize().width / 2)); ⑦
world->addJoint(joint); ⑧
}
上面代碼onTouchBegan函數是觸摸響應函數,在onTouchBegan中調用addNewSpriteAtPosition函數。在addNewSpriteAtPosition中建立兩個精靈,建立兩個物體,並設置它們之間的關節約束。代碼第①行建立精靈boxA,第②行設置它的位置。第③行代碼PhysicsBody::createBox(boxA->getContentSize())是建立矩形盒子物體。第③行代碼boxA->setPhysicsBody(boxABody) 是設置與精靈相關的物體對象。第⑤行是將精靈添加到當前層中。
建立完成boxA和boxABody,下面又緊接着建立了boxB 和boxBBody對象。建立好它們以後就能夠進行添加關節約束了,第⑥行代碼auto world = this->getScene()->getPhysicsWorld()是從場景中得到物理世界(PhysicsWorld)對象。第⑦行代碼經過PhysicsJointDistance的靜態函數construct建立距離關節對象,其中錨點座標採用的模型座標(本地座標),若是得到的不是模型座標,能夠進行座標轉換。PhysicsBody中提供兩個座標轉換函數:
Vec2 world2Local(const Vec2& point)。世界座標轉換爲模型座標。
Vec2 local2World(const Vec2& point)。模型座標轉換爲世界座標。
最後第⑧行代碼world->addJoint(joint)語句是將建立關節添加到物理世界中。
更多內容請關注國內第一本Cocos2d-x 3.2版本圖書《Cocos2d-x實戰:C++卷》
本書交流討論網站:http://www.cocoagame.net
更多精彩視頻課程請關注智捷課堂Cocos課程:http://v.51work6.com
歡迎加入Cocos2d-x技術討論羣:257760386
歡迎關注智捷iOS課堂微信公共平臺