Can you help. Want to draw a polygon (beams at different angles) and apply box 2d body 开发者_如何学Goto it. Can you please let me know how to create a CCSprite with a polygon shape Any examples would help Cheers
Create Polygon body.
-(void) createDynamicPoly { b2BodyDef bodyDefPoly; bodyDefPoly.type = b2_dynamicBody; bodyDefPoly.position.Set(3.0f, 10.0f); b2Body *polyBody = world->CreateBody(&bodyDefPoly); int count = 8; b2Vec2 vertices[8]; vertices[0].Set(0.0f / PTM_RATIO,0.0f / PTM_RATIO); vertices[1].Set(48.0f/PTM_RATIO,0.0f/PTM_RATIO); vertices[2].Set(48.0f/PTM_RATIO,30.0f/PTM_RATIO); vertices[3].Set(42.0f/PTM_RATIO,30.0f/PTM_RATIO); vertices[4].Set(30.0f/PTM_RATIO,18.0f/PTM_RATIO); vertices[5].Set(18.0f/PTM_RATIO,12.0f/PTM_RATIO); vertices[6].Set(6.0f/PTM_RATIO,18.0f/PTM_RATIO); vertices[7].Set(0.0f/PTM_RATIO,30.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); }
Create your sprite
Attach your sprite to the Polygon body via Fixture and UserData
fixtureDefPoly.SetUserData() = spriteObject; b2Fixture *fixture; fixture = circleBody->CreateFixture(&fixtureDefPoly); fixture->SetUserData(@"spriteObject");
Then Iterate the sprite to the body in your update method.
The easiest way is to open an image editor (such as paint for example or photoshop) and create the image you want. The use it in your program.
Also there is a helloWorld scene when creating an xcode application using cocos2d box2d template. It creates a set of squares with a texture.
CGPoint startPt = edge.start ;
CGPoint endpt = edge.end ;
//length of the stick body
float len = abs(ccpDistance(startPt, endpt))/PTM_RATIO;
//to calculate the angle and position of the body.
float dx = endpt.x-startPt.x;
float dy = endpt.y-startPt.y;
//position of the body
float xPos = startPt.x+dx/2.0f;
float yPos = startPt.y+dy/2.0f;
//width of the body.
float width = 1.0f/PTM_RATIO;
b2BodyDef bodyDef;
bodyDef.position.Set(xPos/PTM_RATIO, yPos/PTM_RATIO);
bodyDef.angle = atan(dy/dx);
NSLog([NSString stringWithFormat:@"Setting angle %f",bodyDef.angle]);
CCSprite *sp = [CCSprite spriteWithFile:@"material-wood.png" rect:CGRectMake(0, 0, 12, 12)];
//TODO: fix shape
[self addChild:sp z:1 ];
bodyDef.userData = sp;
bodyDef.type = b2_dynamicBody;
b2Body* body = world->CreateBody(&bodyDef);
b2PolygonShape shape;
b2Vec2 rectangle1_vertices[4];
rectangle1_vertices[0].Set(-len/2, -width/2);
rectangle1_vertices[1].Set(len/2, -width/2);
rectangle1_vertices[2].Set(len/2, width/2);
rectangle1_vertices[3].Set(-len/2, width/2);
shape.Set(rectangle1_vertices, 4);
b2FixtureDef fd;
fd.shape = &shape;
fd.density = 1.0f;
fd.friction = 0.300000f;
fd.restitution = 0.600000f;
body->CreateFixture(&fd);
精彩评论