Box2D地箱

时间:2012-09-13 22:11:11

标签: objective-c ios box2d

我对Box2D很陌生,我试图用一些盒子和地面来制作一个简单的场景,但无论我做什么,盒子都会掉到地上。

这就是我创建Box2D世界的方式:

b2Vec2 gravity;
gravity.Set(0.0f, -9.81f);

bool doSleep = true;

world = new b2World(gravity);
world->SetAllowSleeping(doSleep);
world->SetContinuousPhysics(true);

b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0, 0); // bottom-left corner

b2Body* groundBody = world->CreateBody(&groundBodyDef);

b2EdgeShape groundBox;

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

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

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

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

这就是我如何向场景中添加对象:

b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;

CGPoint p = CGPointMake(sprite.x, sprite.y);

bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
bodyDef.userData = (void*)sprite;

b2Body *body = world->CreateBody(&bodyDef);

b2PolygonShape dynamicBox;

dynamicBox.SetAsBox(sprite.width/PTM_RATIO, sprite.height/PTM_RATIO);

b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 13.0f;
fixtureDef.friction = 0.0f;
fixtureDef.restitution = 0.5f;
body->CreateFixture(&fixtureDef);

body->SetType(b2_dynamicBody);

sprite.physicsBody = body;

这是我的自动收报机:

int32 velocityIterations = 8;
int32 positionIterations = 1;

world->Step(1.0f/60.0f, velocityIterations, positionIterations);

for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
    if (b->GetUserData() != NULL)
    {
        SEPhysicsSprite * sprite = (SEPhysicsSprite*)b->GetUserData();

        CGPoint newCenter = CGPointMake(b->GetPosition().x * PTM_RATIO,
                                        b->GetPosition().y * PTM_RATIO);

        sprite.x = newCenter.x;
        sprite.y = newCenter.y;
        sprite.rotation = b->GetAngle();
    }
}

这应该在屏幕底部创建一个地面,但我的对象才会失败。如果我只是一个触摸屏幕左侧并让它掉落的盒子,它就会碰到一些东西,就像它碰撞的一个小小的像素,只是稍微反弹然后不断下降。

我看过很多关于iphone和c ++等的例子,它们都有类似的初始化代码,我不知道为什么我的代码不能工作。请停下来!

0 个答案:

没有答案