Search code examples
iphonecocos2d-iphonebox2d

Cannot set "setAsEdge" in Box2D on iPhone


This code will create lines around the iPhone screen, but the bottom line should be in the middle (I need to change the .y but I don't know how). How to do that?

And can someone explain these "setAsEdge" methods to me?

// Define the ground body.
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0,0); // bottom-left corner

// Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
b2Body* groundBody = world->CreateBody(&groundBodyDef);

// Define the ground box shape.
b2PolygonShape groundBox;       

// bottom
groundBox.SetAsEdge(b2Vec2(0,0), b2Vec2(screenSize.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);

// top
groundBox.SetAsEdge(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(screenSize.width/PTM_RATIO,screenSize.height/PTM_RATIO));
groundBody->CreateFixture(&groundBox,0);

// left
groundBox.SetAsEdge(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(0,0));
groundBody->CreateFixture(&groundBox,0);

// right
groundBox.SetAsEdge(b2Vec2(screenSize.width/PTM_RATIO,screenSize.height/PTM_RATIO), b2Vec2(screenSize.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);

Solution

  • // bottom
    
    float screenMid = screenSize.height/2;  // Y axis on screen middle
    
            groundBox.SetAsEdge(b2Vec2(0,screenMid/PTM_RATIO),b2Vec2(screenSize.width/PTM_RATIO,screenMid/PTM_RATIO));
    

    This will shift your bottom line to screen middle. The SetAsEdge method takes two points and draw a line from point-1 to point-2. In above statement the point one is "b2Vec2(0,screenMid/PTM_RATIO)". Where 0 is the x-axis and screenMid is the y-axis of first point. Same goes with the second point.

    You have to divide every point by PTM_RATIO to translate it into box2d coordinates.