所以我一直在尝试使用分离轴定理在我的游戏项目中进行碰撞检测和响应。我已经设法检测到碰撞,但对于我的一生,我无法弄清楚如何应对它。我正在尝试找到最小平移向量,但我不确定如何使其成为实际向量,以便我可以计算如何响应碰撞。我已经阅读了一个又一个教程,并且在这里查看了许多以前提出的问题,但我无法弄清楚如何实现它。我很难理解如何找到和使用 MTV,所以如果有人真的可以帮助我理解,也许可以给我一些例子,这样我就可以在实现中理解它,而不仅仅是理论,那就太好了赞赏,对于给您带来的任何不便,我深表歉意。我的代码确实成功地检测到了碰撞,它在下面:
//NOTE: This is within the HitPolygon class, so "this" is referencing itself as a polygon
public Projection project(Vector2D axis){
float min = axis.dot(this.getVertices().get(0));
float max = min;
Vector2D vecMax = new Vector2D(0, 0), vecMin = new Vector2D(0, 0);
for(int i = 1; i < this.getVertices().size(); i++){
float p = axis.dot(this.getVertices().get(i));
if(p < min){
min = p;
vecMin = this.getVertices().get(i);
}
if(p > max){
max = p;
vecMax = this.getVertices().get(i);
}
}
Projection result = new Projection(min, max, vecMin, vecMax, axis);
return result;
}
public boolean contains(Projection p1, Projection p2){
return(p1.min >= p2.min && p1.min <= p2.max) || (p1.max >= p2.min && p1.max <= p2.max);
}
public boolean overlap(Projection a, Projection b){
if(contains(a, b)) return true;
if(contains(b, a)) return true;
return false;
}
public boolean collide(HitPolygon b){
ArrayList<Vector2D> axes1 = this.getAxes(0);
ArrayList<Vector2D> axes2 = b.getAxes(0);
for(int i = 0; i < axes1.size(); i++){
Vector2D axis = axes1.get(i);
Projection p1 = this.project(axis), p2 = b.project(axis);
if(!overlap(p1, p2)) return false;
else{
float start = p1.min > p2.min ? p1.min : p2.min;
float end = p1.max < p2.max ? p1.max : p2.max;
float translation = end - start;
//translation might be the MTV, more or less, but it's not a vector and I don't know how to turn it into one.
}
}
for(int i = 0; i < axes2.size(); i++){
Vector2D axis = axes2.get(i);
Projection p1 = this.project(axis), p2 = b.project(axis);
if(!overlap(p2, p1)) return false;
else{
}
}
System.out.println("collide");
return true;
}
这是简单的投影类:
class Projection{
public Vector2D minVec, maxVec;
public float min, max;
public Vector2D axis = new Vector2D(0, 0);
public Projection(float min, float max, Vector2D minVec, Vector2D maxVec, Vector2D axis){
this.min = min;
this.max = max;
this.minVec = minVec;
this.maxVec = maxVec;
this.axis = axis;
}
public float minDot(){
return axis.dot(minVec);
}
public float maxDot(){
return axis.dot(maxVec);
}
}
如果需要任何额外的代码,我很乐意提供。请原谅我对如何查找和使用 MTV 缺乏了解,但我们非常感谢任何帮助。谢谢!