一个身体或多个身体上有多个固定装置?

Gat*_*per 10 java performance android box2d libgdx

假设我想在屏幕上创建1000条甚至5000条静态身体线条.我想知道的是,将所有这些线(固定装置)连接到单个主体上,或将每个固定装置放在自己的主体上有什么区别.两种方法之间是否存在性能差异,或者一种方法是否提供了更多功能或控制其他方法?

下面显示了两种方法之间的差异.

将每一条线连接到一个体上:

    // Create our body definition
    BodyDef groundBodyDef = new BodyDef();
    groundBodyDef.type = BodyType.StaticBody;

    // Create a body from the defintion and add it to the world
    Body groundBody = world.createBody(groundBodyDef);

    for (int i = 0; i < 1000; i++) {
        // Create our line
        EdgeShape ground = new EdgeShape();
        ground.set(x1, y1, x2, y2);
        groundBody.createFixture(ground, 0.0f);
        ground.dispose();
    }
Run Code Online (Sandbox Code Playgroud)

将每条线连接到自己的身体:

    // Create our body definition
    BodyDef groundBodyDef = new BodyDef();
    groundBodyDef.type = BodyType.StaticBody;

    for (int i = 0; i < 1000; i++) {
        // Create a body from the defintion and add it to the world
        Body groundBody = world.createBody(groundBodyDef);

        // Create our line
        EdgeShape ground = new EdgeShape();
        ground.set(x1, y1, x2, y2);
        groundBody.createFixture(ground, 0.0f);
        ground.dispose();
    }
Run Code Online (Sandbox Code Playgroud)

这个代码示例特别是在libGDX中,但我想这是一个相当基本的box2D概念,即使没有libGDX经验也可以回答.

一个可能的功能差异的一个例子是,如果所有的线都连接到一个单体并且我们要调用world.destroyBody(groundBody);它,它也会破坏所有线,但是如果每条线连接到不同的体,我们只会销毁一条线.

这甚至会产生实质性的差异吗?groundBody.destroyFixture(fixture);如果它们全部连接到一个体,我们可以简单地调用以销毁一条线.

Les*_*tat 10

来自Box2D手册(7.3 Body Factory):

将多个形状附加到静态主体比创建几个静态主体更快,每个静态主体上都有一个形状.在内部,Box2D将静态物体的质量和反质量设置为零.这使得数学运算成为可能,因此大多数算法不需要将静态实体视为特殊情况.

它的性能确实更高.它引人注目吗?取决于,如果你有很多身体有一个固定装置,你可以让它们成为一个单一的固定装置,但可能不适用于大多数游戏.

我建议你使用一个更容易实现的,并且只在你真正需要它时才能使它更高效.

  • +1关于引用和关于过早优化的警告. (2认同)