【问题标题】:How do you change the edges of a ground fixture in a box2d ground body如何更改 box2d 地面主体中地面夹具的边缘
【发布时间】:2013-02-25 17:55:00
【问题描述】:

在玩游戏期间,我希望能够更改 Box2D 世界中的地面边缘。我已经创建了一个地面主体,然后我在主体上添加了一个地面固定装置。例如,下面的代码将在我的 Box2D 世界中创建一个高于屏幕底部 20 像素的平坦地面:

b2BodyDef groundBodyDef;
groundBodyDef.type = b2_staticBody;
groundBodyDef.position.Set(0, 0);
groundBody = world->CreateBody(&groundBodyDef);

b2PolygonShape groundShape;
b2FixtureDef groundFixtureDef;
groundFixtureDef.shape = &groundShape;
groundFixtureDef.density = 0.0;

CGSize screenSize = [CCDirector sharedDirector].winSize;
int num = 2;
b2Vec2 verts[] = {
    b2Vec2(-screenSize.width / 100.0, 20.0 / 100.0),   
    b2Vec2(screenSize.width / 100.0, 20.0 / 100.0)
};

for(int i = 0; i < num - 1; ++i) {
    b2Vec2 offset = b2Vec2(screenSize.width/2/PTM_RATIO,
                           20.0/2/PTM_RATIO);
    b2Vec2 left = verts[i] + offset;
    b2Vec2 right = verts[i+1] + offset;

    groundShape.SetAsEdge(left, right);
    groundBody->CreateFixture(&groundFixtureDef);
}

假设我需要更改 verts 数组以具有不同的地面夹具定义?例如,是否可以在玩家的移动之间动态地将地面抬高 50 像素?我是否需要删除整个地基体并重新创建地基体和夹具,或者我可以删除或修改现有的地基夹具?

【问题讨论】:

    标签: ios cocos2d-iphone box2d


    【解决方案1】:

    我发现它可以破坏当前的groundBody,然后创建一个新的groundBody,并且ground fixture可以正常工作。我不知道这是否最有利于性能,但它就像我想要的那样工作。

    所以基本上,在我的游戏中的适当时间,我会做以下事情:

        world->DestroyBody(groundBody);
    

    然后我重新执行上面问题陈述中显示的代码,将 verts 数组中的 20.0 像素值替换为 50.0 像素值,如下所示:

    b2Vec2 verts[] = {
        b2Vec2(-screenSize.width / 100.0, 50.0 / 100.0),   
        b2Vec2(screenSize.width / 100.0, 50.0 / 100.0)
    }
    

    【讨论】:

      【解决方案2】:

      将 b2PolygonShape 更改为 b2EdgeShape。

      CGSize s = [[CCDirector sharedDirector] winSize];
      b2EdgeShape groundBox;
      
      // bottom
      groundBox.Set(b2Vec2(0.0f,0.0f), b2Vec2(s.width/PTM_RATIO,0.0f));
      groundBody->CreateFixture(&groundBox,0);
      

      您不能在运行时更改夹具定义。因此,请使用不同的夹具并在运行时切换该主体。

      【讨论】:

      • 您是否建议我创建 2 个不同的地面主体(每个都有自己的固定装置)并在运行时切换主体?如果是这样,您如何执行切换?
      猜你喜欢
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多