0

我对 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++ 等的示例,它们都有类似的初始化代码,我不明白为什么我的代码不起作用。请停下来!

4

0 回答 0