Cocos2d使用CCSprite绘制多边形

时间:2011-03-19 02:24:07

标签: cocos2d-iphone polygon box2d ccsprite

你能帮忙吗?想要绘制多边形(不同角度的光束)并将框2d体应用于它。你能告诉我如何创建一个多边形的CCSprite 任何例子都会有帮助 干杯

3 个答案:

答案 0 :(得分:2)

  1. 创建多边形体。

    -(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);    
    }
    
  2. 创建精灵

  3. 通过Fixture和UserData

    将您的精灵附加到Polygon身体
    fixtureDefPoly.SetUserData() = spriteObject;  
    b2Fixture *fixture;  
    fixture = circleBody->CreateFixture(&fixtureDefPoly);  
    fixture->SetUserData(@"spriteObject");  
    
  4. 然后在更新方法中将精灵迭代到正文。

答案 1 :(得分:0)

最简单的方法是打开图像编辑器(例如绘画或photoshop)并创建所需的图像。在你的程序中使用它。

使用cocos2d box2d模板创建xcode应用程序时,还有一个helloWorld场景。它创建了一组带纹理的正方形。

答案 2 :(得分:0)

    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);