假设我想在屏幕上创建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(); }
将每条线连接到自己的身体:
// 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,0.0f); ground.dispose(); }
这个代码示例特别在libGDX中,但是我想象这是一个相当基本的Box2D概念,即使没有libGDX体验也可以回答.
可能的功能差异的一个例子是,如果所有行都附加到单个主体,并且我们调用world.destroyBody(groundBody);它也会销毁所有行,但是如果每行都附加到不同的身体,我们只会破坏一条线.
即使这样做有很大的不同吗?我们可以简单地调用groundBody.destroyFixture(fixture);如果它们都连接到单个身体,则销毁一条线.
解决方法
从
Box2D Manual(7.3车身厂):
It is faster to attach several shapes to a static body than to create
several static bodies with a single shape on each one. Internally,
Box2D sets the mass and inverse mass of static bodies to zero. This
makes the math work out so that most algorithms don’t need to treat
static bodies as a special case.
这确实比较好.很明显吗取决于,如果你有很多身体与一个夹具,你使他们的一个单一的身体,但可能不是大多数游戏.