gpt4 book ai didi

java - Box2D 中的碰撞检测

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:37:44 24 4
gpt4 key购买 nike

所以我在游戏中使用 Box2D 进行碰撞检测。我有一个包含地形信息的 tilemap:现在它只是一个有道路或草地的 char[][]。现在,在每个级别的开始,我想创建矩形来描述不同的地形,但我希望优化这些矩形,显然这需要相当多的算法。

我的第一个方法是在关卡开始时为 map 中的每个方 block 创建单独的地形。 FPS 降低到 5。

我的第二个想法是当玩家沿着 map 移动时简单地为地形创建不同的矩形,删除视野之外的矩形。虽然它仍然会有很多矩形,但会少得多。

我还没有尝试过第二种方法,但我想知道:有没有什么简单的方法可以让我有效地对具有大瓦片 map 的地形执行碰撞检测?

谢谢。

最佳答案

尝试组合图 block 。例如,如果您有 16 个矩形碰撞体,用于 16 个图 block ,就像这样...

* * * *
* * * *
* * * *
* * * *

您显然可以将这些图 block 组合成一个大矩形。

现在,如果您的瓷砖排列方式很奇怪,事情就会变得更加困难,可能像这样......

**---
****-
*--**
-*-*-

我最近刚刚在我的游戏中使用 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);
}
}

关于java - Box2D 中的碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17847830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com