主要用到这两个函数
取精灵的顶点信息 : AutoPolygon::generatePolygon();
创建多边形钢体 : PhysicsBody::createPolygon();
因为第一个函数取出来的信息不能直接作为第二个函数的参数,所以自己重新创建了Vec2数组,然后把获取的顶点信息里面的 顶点重新赋值给Vec2数组,而且实际测试中物理刚体会偏移,自己试了下 X, Y各减去一半,就好了.(不知道为什么,求大神解答)
下面是代码
void sprite_base::bindPhysicsBody(Node* pNode, std::string pFileName,unsigned int pContactTestBitmask,bool pGravity)
{
auto tSize=pNode->getContentSize();
//pNode要绑定刚体的精灵 pFileName是精灵的图片文件路径
//Polygon
auto tPolygon = AutoPolygon::generatePolygon(pFileName, Rect(0, 0, tSize.width, tSize.height));
const auto count = tPolygon.triangles.indexCount;
const auto indices = tPolygon.triangles.indices;
const auto verts = tPolygon.triangles.verts;
//points
Vec2* tPoints = new Vec2[count];
for (int i = 0; i < count; i++)
{
tPoints[i].x = verts[indices[i]].vertices.x - pNode->getContentSize().width / 2;
tPoints[i].y = verts[indices[i]].vertices.y - pNode->getContentSize().height / 2;
}
//body
auto tPhysicsBody = PhysicsBody::createPolygon(tPoints, count);
tPhysicsBody->getFirstShape()->setMaterial(PhysicsMaterial(0.1, 0.0, 0.5));
tPhysicsBody->setContactTestBitmask(pContactTestBitmask);
tPhysicsBody->setRotationEnable(false);
tPhysicsBody->setGravityEnable(pGravity);
pNode->setPhysicsBody(tPhysicsBody);
delete []tPoints;
}
求大神指正...