[英]Java 2d polygon collision response
我制作了一个使用凸多边形的游戏。 我的计划是让这些多边形根据其质量和速度发生碰撞和反弹。 但是首先我需要确保它们没有重叠。 此代码检查多边形A的每个边缘,以查看多边形B的任何顶点在垂直于该边缘的轴上是否重叠。 整个方法返回修复多边形A所需的结果Vector:
/**Calculates adjustment vector for EntityPolygon A*/
public Vector calculateCollision(EntityPolygon A, EntityPolygon B) {
//this is a large number so the first comparison of overlap is true
double overlap = 10000;
//this is the angle of the axis to apply the overlap vector
double angle = 0;
//I ran a for loop for every edge of the polygon
for(int x = 0; x <= A.numPoint - 1; x++) {
//create variables
Vector edge;
Vector axis;
double centerA;
double centerB;
double maxA;
double maxB;
double minA;
double minB;
//this if statement finds this point and the next point
//to make a Vector of the edge
if(x != A.numPoint - 1) {
edge = new Vector(A.point[x], A.point[x + 1]);
} else {
edge = new Vector(A.point[x], A.point[0]);
}
//this finds the axis perpendicular axis of the edge
axis = edge.getRightNormal();
//finds the location of both polygon's centers when projected onto
//the velocity(projectionOnVelocity() projects the point on the
//new axis)
centerA = A.getLocation().getProjectionOnVelocity(axis);
centerB = B.getLocation().getProjectionOnVelocity(axis);
//finds the location of polygons A and B on the axis by
//setting the min and max of their highest and lowest points
maxA = findMax(A, axis);
maxB = findMax(B, axis);
minA = findMin(A, axis);
minB = findMin(B,axis);
//final comparison to find overlapping vector.
if(centerA > centerB) {//if A is above B on the axis
if(maxB > minA) {//if the max point on B is above min on A
double m = maxB - minA;
if(m < overlap) {
overlap = m;
angle = axis.angle;
}
} else {
//(0,0) vector
return Vector.getDefault();
}
} else if(centerB > centerA) {//if B is above A on axis
if(maxA > minB) {//if the max point on A is above min on B
double m = maxA - minB;
if(m < overlap) {
overlap = m;
angle = axis.angle + Math.PI;
}
} else {
//(0,0) vector
return Vector.getDefault();
}
}
}
//if the overlap value has been set by the edges of Polygon A
if(overlap != 10000) {
//returns the adjustment vector along overlap edge axis
return new Vector(angle, overlap, true);
} else {
(0,0) vector
return Vector.getDefault();
}
}
这段代码有一个错误,当一个非常平坦的块位于一个正方形块之上时,该错误会导致问题,而该平坦块认为它比实际下降的要远得多。 结果,平板和正方形发生碰撞,将它们推到下图中的当前位置
这是初步阶段的实际游戏的图片。 甚至触摸之前,右侧的蓝色方块已被顶部的障碍物移动。 当正方形在屏幕的最左侧时,这会在程序开始时发生。
我同意Beta,您的算法看起来不正确(主要是因为我敢肯定多边形的交点不会那么容易。仅对于检查2个形状的交点(没有任何智能),您必须检查是否有任何边缘相交)具有其他形状的任何边缘,但这即使是中等简单的形状也很慢。
矩形相交是很容易做到的,三角形相交应该不会太难,如果您可以将形状拆分为其中的一个(或者实际上是一组具有相当简单公式的形状),它将使事情变得容易得多。
您也可以查看此问题 。
多边形相交是一个经过充分研究的问题,只是Google,您应该有很多选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.