如何检查两个顶点列表是否相交? 我正在使用它来检查游戏中的实体是否相互碰撞
package com.indigoa.lwjgl.gamelib.world.boundingbox;
import java.util.ArrayList;
import java.util.List;
import org.joml.Vector3f;
import com.indigoa.lwjgl.gamelib.SimpleFunctions;
public class BoundingBox {
public List<Vector3f> postions;
public BoundingBox(float[] vertices) throws Exception {
this(SimpleFunctions.toListF(vertices));
}
public BoundingBox(List<Float> vertices) throws Exception {
if (Float.toString(vertices.size() / 3).contains(".")) {
throw new Exception("Vertices are not divisible by 3, and therefore cannot be converted into points.");
}
}
public BoundingBox(Vector3f... positions) {
this.postions = new ArrayList<Vector3f>();
for (Vector3f p : positions) {
this.postions.add(p);
}
public AxisAlignedBoundingBox toAABB() {
Vector3f min = new Vector3f(), max = new Vector3f();
for (Vector3f pos : postions) {
if (pos.x < min.x) min.x = pos.x;
if (pos.y < min.y) min.y = pos.y;
if (pos.z < min.z) min.z = pos.z;
if (pos.x > max.x) max.x = pos.x;
if (pos.y > max.y) max.y = pos.y;
if (pos.z > max.z) max.z = pos.z;
}
return new AxisAlignedBoundingBox(min, max);
}
public boolean doBoesIntersect(BoundingBox boundingbox) {
return false; // TODO
}
}
我需要弄清楚的是如何检查边界框是否相交,并且我不想对合并的所有顶点使用最小和最大位置。如何确定点列表是否相交?
当前,我使用这个:
public boolean doBoxesIntersect(BoundingBox boundingbox) {
return toAABB().doBoxesIntersect(boundingbox);
}
AxisAlignedBoundingBox:
package com.indigoa.lwjgl.gamelib.world.boundingbox;
import java.util.ArrayList;
import java.util.List;
import org.joml.Vector3f;
public class AxisAlignedBoundingBox extends BoundingBox {
public AxisAlignedBoundingBox(Vector3f pos1, Vector3f pos2) {
positions.add(pos1);
positions.add(new Vector3f(pos2.x, pos1.y, pos1.z));
positions.add(new Vector3f(pos1.x, pos2.y, pos1.z));
positions.add(new Vector3f(pos1.x, pos1.y, pos2.z));
positions.add(pos2);
positions.add(new Vector3f(pos1.x, pos2.y, pos2.z));
positions.add(new Vector3f(pos2.x, pos1.y, pos2.z));
positions.add(new Vector3f(pos2.x, pos2.y, pos1.z));
}
public AxisAlignedBoundingBox(float x1, float y1, float z1, float x2, float y2, float z2) {
this(new Vector3f(x1, y1, z1), new Vector3f(x2, y2, z2));
}
public boolean doBoxesIntersect(BoundingBox boundingbox) {
List<Vector3f> positions = new ArrayList<Vector3f>();
Vector3f pos1 = this.postions.get(0);
Vector3f pos2 = this.postions.get(1);
positions.addAll(boundingbox.toAABB().postions);
for (Vector3f position : positions) {
if (position.x > pos1.x && position.x < pos2.x) {
if (position.y > pos1.y && position.y < pos2.y) {
if (position.z > pos1.z && position.z < pos2.z) {
return true;
}
}
} else if (position.x > pos2.x && position.x < pos1.x) {
if (position.y > pos2.y && position.y < pos1.y) {
if (position.z > pos2.z && position.z < pos1.z) {
return true;
}
}
}
}
return false;
}
}
该系统存在缺陷,因为每次将边界框转换为AABB时,其精度都比普通边界框低。
我将第二个边界框转换为AABB,因此在检查冲突时没有任何差异。