The Basic Usage of Box2D for iPhone/iPad Project.

Hi, All

I just start to learn Box2D for my own iPhone Projects.

What I got understanding is ...
1. Create the "world".
2. Create the "Walls".
3. And I success to move "UIView" Objects, adding to self.view, automatically with gravity I set.

So, I've deside to use b2CircleShape for next step.
The code i wrote is build sucess, but any circles does't appear.....

Any advice !

My code is following..

Code: Select all


-(void)createPhysicsWorld
{
        CGSize screenSize = self.view.bounds.size;
   
   // Define the gravity vector.
   b2Vec2 gravity;
   gravity.Set(0.0f, -9.81f);
   
   // Do we want to let bodies sleep?
   // This will speed up the physics simulation
   bool doSleep = true;
   
   // Construct a world object, which will hold and simulate the rigid bodies.
   world = new b2World(gravity, doSleep);
   
   world->SetContinuousPhysics(true);
   
   // 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.
   b2EdgeShape groundBox;
   
   // bottom
   groundBox.Set(b2Vec2(0,0), b2Vec2(screenSize.width/PTM_RATIO,0));
   groundBody->CreateFixture(&groundBox, 0);
   
   // top
   groundBox.Set(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(screenSize.width/PTM_RATIO,screenSize.height/PTM_RATIO));
   groundBody->CreateFixture(&groundBox, 0);
   
   // left
   groundBox.Set(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(0,0));
   groundBody->CreateFixture(&groundBox, 0);
   
   // right
   groundBox.Set(b2Vec2(screenSize.width/PTM_RATIO,screenSize.height/PTM_RATIO), b2Vec2(screenSize.width/PTM_RATIO,0));
   groundBody->CreateFixture(&groundBox, 0);
}


- (void)createCircle
{
    //Circle
    b2FixtureDef _fixtureDef;
    b2CircleShape circleDef;
   
    _fixtureDef.friction = 10;
    _fixtureDef.density = 10;
    _fixtureDef.restitution = 0.9;
    _fixtureDef.shape = &circleDef;
   
    b2BodyDef bodyDef;
   bodyDef.type = b2_dynamicBody;
   
    circleDef.m_radius = 5.0;
    bodyDef.position.Set(20/PTM_RATIO, (460.0 - 50)/PTM_RATIO);
   
    b2Body *circleBody = world->CreateBody(&bodyDef);
    circleBody->CreateFixture(&_fixtureDef);
}

- (void)viewDidLoad
{
   [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
   
    [self createPhysicsWorld];  // create the world
    [self createCircle];             // create the circle
}

What are you using to draw the circles? Do you draw a circle inside the UIView?

You can use the debug draw callback if you want to let Box2D tell you the exact locations to draw - see some details here: http://www.iforce2d.net/b2dtut/debug-draw

Or, you can use body->GetPosition() every frame to get the current position yourself to draw the circle.

Either way, Box2D does not do any drawing for you, so you need to manage that yourself.

Box2DをiOSで使う情報が少ないのは多分、C++ならば他のOSと特に変わりがないからです。自分もcocos2dに興味がなく、UIKit+OpenGLで使っています。ちなみにUIViewを動かしていると聞いたら以下のページを思い出した。ご参考になれれば....
http://www.cocoanetics.com/2010/05/phys ... r-gravity/
Thanks for your reply !
こんにちは。アドバイスありがとうございます。

教えていただいたUIKitのオブジェクトを動かすサンプルURLは、チェック済みだったのですが、
その後、box2dのデフォルトシェイプ?のcircleを表示したいと思っているのですが、

まず、ver2.2になってからdebug draw callbackがなくなっている!ので、
b2Drawを使えばいいのかな…とおもって書いているのですが、

表示ができないでいます。

四方の壁は、

Code: Select all

- (void)createWall
{
    // ScreenSize
    CGSize screenSize = self.view.bounds.size;
   
    // 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.
   b2EdgeShape groundBox;
   
   // bottom
   groundBox.Set(b2Vec2(0,0), b2Vec2(screenSize.width/PTM_RATIO,0));
   groundBody->CreateFixture(&groundBox, 0);
   
   // top
   groundBox.Set(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(screenSize.width/PTM_RATIO,screenSize.height/PTM_RATIO));
   groundBody->CreateFixture(&groundBox, 0);
   
   // left
   groundBox.Set(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(0,0));
   groundBody->CreateFixture(&groundBox, 0);
   
   // right
   groundBox.Set(b2Vec2(screenSize.width/PTM_RATIO,screenSize.height/PTM_RATIO), b2Vec2(screenSize.width/PTM_RATIO,0));
   groundBody->CreateFixture(&groundBox, 0);
}



な感じでつくっていまして、

worldは、

Code: Select all

- (void)createWorld
{
   // Define the gravity vector.
   b2Vec2 gravity;
   gravity.Set(0.0f, -9.81f);
   
   // Do we want to let bodies sleep?
   // This will speed up the physics simulation
   bool doSleep = true;
   
   // Construct a world object, which will hold and simulate the rigid bodies.
   world = new b2World(gravity, doSleep);
   
   world->SetContinuousPhysics(true);
   
    m_debugDraw.SetFlags(b2Draw::e_shapeBit);
   world->SetDebugDraw( &m_debugDraw );
}


としています。
肝心のcircleは、

Code: Select all

- (void)createBasicCircle
{
   
    // Define the dynamic body.
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
   
//   CGPoint p = physicalView.center;
    CGPoint p = CGPointMake(100, 100);

    bodyDef.position.Set(p.x/PTM_RATIO, (460.0 - p.y)/PTM_RATIO);
   
   // Tell the physics world to create the body
   b2Body *body = world->CreateBody(&bodyDef);
   
    b2CircleShape  circleShape;
    circleShape.m_radius = 20.0/PTM_RATIO;
   
   // Define the dynamic body fixture.
   b2FixtureDef fixtureDef;
   fixtureDef.shape = &circleShape;
   fixtureDef.density = 3.0f;
   fixtureDef.friction = 0.3f;
   fixtureDef.restitution = 0.5f;
   body->CreateFixture(&fixtureDef);
   
   // a dynamic body reacts to forces right away
    body->SetType(b2_dynamicBody);
}


それで1/60間隔で、tick();を実行して更新しています。

Code: Select all

- (void)tick
    int32 velocityIterations = 8;
    int32 positionIterations = 1;
    world->Step(1.0f/60.0f, velocityIterations, positionIterations);
    world->DrawDebugData();


MyDebugDrawクラスは、
●MyDebugDraw.h

Code: Select all

#include <Box2D/Box2D.h>

class MyDebugDraw : public b2Draw
{
public:
    void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) {}
    void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
    void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) {}
    void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) {}
    void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) {}
    void DrawTransform(const b2Transform& xf) {}
};


●MyDebugDraw.cpp

Code: Select all

void MyDebugDraw::DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color)
{
   
    //set up vertex array
    GLfloat glverts[16]; //allow for polygons up to 8 vertices
    glVertexPointer(2, GL_FLOAT, 0, glverts); //tell OpenGL where to find vertices
    glEnableClientState(GL_VERTEX_ARRAY); //use vertices in subsequent calls to glDrawArrays
   
    //fill in vertex positions as directed by Box2D
    for (int i = 0; i < vertexCount; i++) {
      glverts[i*2]   = vertices[i].x;
      glverts[i*2+1] = vertices[i].y;
    }
   
   glEnable(GL_BLEND);
   glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
   
    //draw solid area
    glColor4f( color.r, color.g, color.b, 0.5f );
    glDrawArrays(GL_TRIANGLE_FAN, 0, vertexCount);
   
    //draw lines
   glColor4f( color.r, color.g, color.b, 1 );
    glDrawArrays(GL_LINE_LOOP, 0, vertexCount);
}


としています。
circleだから、DrawSolidPolygonを実装するのではなくて、DrawCircleを実装しないとだめかなと
思うのですが、考え方自体がそもそもあっているのでしょうか。。。。

よろしくお願いいたします。
Yes, you need to implement the circle drawing function too.

You can find an example for OpenGL ES in the Box2D source code, in the folder Contributions/Platforms/iPhone/Classes

自分で実装した後にそのフォルダに気がついた。私のより少し簡潔なのでお進めします。
ちなみに私が作った方をXCodeプロジェクトとしてゲットできます:http://www.iforce2d.net/blog/2011-07-30
Try this tutorial

Original thread: https://box2d.org/forum/viewtopic.php?t=7357