在運用實體引擎的時候,經常回出現這種情況,不規則物體的碰撞檢測無法更加精确的測量,那麼,小傑今天就帶您一起解決這個問題!!!
首先下載下傳一個windows下面的軟體 名稱是:PhysicsEditor ,這個軟體可以幫助你設計不規則的圖形。軟體的使用方法在這裡不具體講解了,說一下注意的問題,添加進精靈後 :按照這個步驟走

好了,這時候 做完了就會生成 plist檔案,把它和png圖檔一起拷進資源目錄下面:
定義一個成員方法:
std::vector<std::vector<Vec2>> getShapeFromPlistFile(std::string fileName);
實作:
std::vector<std::vector<Vec2>> Chipmunck::getShapeFromPlistFile(std::string fileName){
std::vector<std::vector<Vec2>> vectors;
//從檔案中讀取plist檔案,将内容讀取到 vec中
ValueVector vec = FileUtils::getInstance()->getValueVectorFromFile(fileName);
for (int i =0;i<vec.size();i++){//周遊vec,得到所有的形狀
ValueVector shape = vec.at(i).asValueVector();
std::vector<Vec2> points;
for (int j=0;j<shape.size();j++){//周遊形狀,拿到所有的點
Vec2 point = PointFromString(shape.at(j).asString());
points.push_back(point);//所有的點放在集合中
}
vectors.push_back(points);//所有的 形狀 放在集合中
}
return vectors;
}
調用它:
void Chipmunck::addSprites(){
auto circleSp = Sprite::create("c.png");
circleSp->setPosition(visSize.width/2,visSize.height/2);
this->addChild(circleSp);
auto body = PhysicsBody::createCircle(circleSp->getContentSize().width/2);
body->setMass(10000);
body->setVelocity(Vec2(0,-1000));
circleSp->setPhysicsBody(body);
auto circleSp2 = Sprite::create("c.png");
circleSp2->setPosition(visSize.width/2,20);
this->addChild(circleSp2);
auto body2 = PhysicsBody::createCircle(circleSp->getContentSize().width/2);
body2->setMass(10000);
body2->setDynamic(false);
circleSp2->setPhysicsBody(body2);
auto paoku = Sprite::create("paoku 00188.png");
paoku->setPosition(Vec2(300,200));
this->addChild(paoku);
//通過傳過去檔案名字 擷取 傳回來的 所有 圖形的集合(每個圖形中存放着很多組成這個圖形的所有的點)
std::vector<std::vector<Vec2>> shapes = this->getShapeFromPlistFile("test.plist");
//定義一個剛體
auto ployon = PhysicsBody::create();
for (auto shape:shapes){//周遊圖形集合中的每個 圖形
//這裡的shape.data是一個指向 第一個元素的指針
auto points = PhysicsShapePolygon::create(shape.data(),(int)shape.size());//根據這個圖形建立剛體
//points是一個點的數組
ployon->addShape(points);//把所有的 放在 剛體中
}
paoku->setPhysicsBody(ployon);
}
好了,這樣基本就解決了!!,運作如圖: