尝试组合瓷砖。举例来说,如果你有16个区块,像这样的16分矩形碰撞体...
* * * *
* * * *
* * * *
* * * *
您可以将这些瓷砖明显合并成一个大的矩形。
现在,事情变得更加困难,如果你在一个奇怪的安排有瓷砖,也许是这样的...
**---
****-
*--**
-*-*-
我刚刚使用quad tree和sweep and prune解决了这个问题,在我的游戏。 (扫描和修剪不是必须的,它是一种优化。)
Quad tree将您的正方形瓷砖划分为更大的矩形,然后遍历四叉树生成的矩形,如果它们具有相同的宽度,则将它们组合在一起再次迭代它们并将它们组合到相似的高度。重复,直到你不能再组合它们,然后产生你的碰撞体积。
Here's a link to a question我问了一个更优化的减少。我可能不会实现这个,因为听起来很难,而且我目前的方法运作良好。
一些代码:
do {
lastCompressSize = currentOutput;
this.runHorizontalCompression(this.output1, this.output2);
this.output1.clear();
this.runVerticalCompression(this.output2, this.output1);
this.output2.clear();
currentOutput = this.output1.size;
iterations += 1;
}while (lastCompressSize > currentOutput);
public void runHorizontalCompression(Array<SimpleRect> input,
Array<SimpleRect> output) {
input.sort(this.xAxisSort);
int x2 = -1;
final SimpleRect newRect = this.rectCache.retreive();
for (int i = 0; i < input.size; i++) {
SimpleRect r1 = input.get(i);
newRect.set(r1);
x2 = newRect.x + newRect.width;
for (int j = i + 1; j < input.size; j++) {
SimpleRect r2 = input.get(j);
if (x2 == r2.x && r2.y == newRect.y
&& r2.height == newRect.height) {
newRect.width += r2.width;
x2 = newRect.x + newRect.width;
input.removeIndex(j);
j -= 1;
} else if (x2 < r2.x)
break;
}
SimpleRect temp = this.rectCache.retreive().set(newRect);
output.add(temp);
}
}
public void runVerticalCompression(Array<SimpleRect> input,
Array<SimpleRect> output) {
input.sort(this.yAxisSort);
int y2 = -1;
final SimpleRect newRect = this.rectCache.retreive();
for (int i = 0; i < input.size; i++) {
SimpleRect r1 = input.get(i);
newRect.set(r1);
y2 = newRect.y + newRect.height;
for (int j = i + 1; j < input.size; j++) {
SimpleRect r2 = input.get(j);
if (y2 == r2.y && r2.x == newRect.x
&& r2.width == newRect.width) {
newRect.height += r2.height;
y2 = newRect.y + newRect.height;
input.removeIndex(j);
j -= 1;
} else if (y2 < r2.y)
break;
}
SimpleRect temp = this.rectCache.retreive().set(newRect);
output.add(temp);
}
}
多大的tilemap的?我做了1000x1000的瓷砖。 –
只需在Box2D中一次添加它们全部?哇,这很令人印象深刻。我正在使用可怜的100x100。 – helsont
您可以使用形状类的重叠方法。这不是它所称的,但我忘记了它的名字。它在javadoc的形状。 –