在cocos2d中更改动态多边形中的多边形顶点

时间:2012-01-31 03:31:15

标签: cocos2d-iphone

我是cocos2d的新手,首先我学会了如何制作一个圆形然后是一个正方形,现在我学会了如何使用" b2多边形多边形"来创建一个具有大量顶点的多边形。这是我的代码

-(void) createDynamicPoly:(CGPoint)p;
{

b2BodyDef bodyDefPoly;
bodyDefPoly.type = b2_dynamicBody; 
bodyDefPoly.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
b2Body *polyBody = world->CreateBody(&bodyDefPoly);

int count = 8;
b2Vec2 vertices[8];

vertices[0].Set(10.0f/PTM_RATIO,0.0/PTM_RATIO);
vertices[1].Set(20.0f/PTM_RATIO,0.0f/PTM_RATIO);
vertices[2].Set(30.0f/PTM_RATIO,10.0f/PTM_RATIO);
vertices[3].Set(30.0f/PTM_RATIO,20.0f/PTM_RATIO); 
vertices[4].Set(20.0f/PTM_RATIO,30.0f/PTM_RATIO);
vertices[5].Set(10.0f/PTM_RATIO,30.0f/PTM_RATIO); 
vertices[6].Set(00.0f/PTM_RATIO,20.0f/PTM_RATIO);
vertices[7].Set(0.0f/PTM_RATIO,10.0f/PTM_RATIO);

b2PolygonShape polygon; 
polygon.Set(vertices, count);

b2FixtureDef fixtureDefPoly;
fixtureDefPoly.shape = &polygon;
fixtureDefPoly.density = 1.0f;
fixtureDefPoly.friction = 0.3f;
polyBody->CreateFixture(&fixtureDefPoly);


}

我的问题是如何主动更改此多边形的顶点并更改屏幕上的形状,而不绘制新形状。我的目标是创造一个自由流动的blob。

三江源

1 个答案:

答案 0 :(得分:2)

修改最后一个语句以返回指向生成的b2Fixture对象的指针。这可以保存为类变量(即类接口中的b2Fixture * fixture)。

fixture = polyBody->CreateFixture(&fixtureDefPoly);

然后,无论您想要更改多边形形状的顶点,请抓住指向与灯具关联的形状对象的指针:

b2PolygonShape* shape = (b2PolygonShape*) fixture->GetShape();

并根据需要修改顶点:

shape->m_vertices[0].Set(new_x0/PTM_RATIO,new_y0/PTM_RATIO); 
shape->m_vertices[1].Set(new_x1/PTM_RATIO,new_y1/PTM_RATIO); 
shape->m_vertices[2].Set(new_x2/PTM_RATIO,new_y2/PTM_RATIO); 
...
shape->m_vertices[7].Set(new_x7/PTM_RATIO,new_y7/PTM_RATIO); 
祝你好运!