我正在尝试完成碰撞检测。我没有使用OpenGl,我正在使用canvas / surfaceview。
我有2个位图。 这是我到目前为止所做的:
public boolean inBounds(int x2,int y2, int x,int y,int width,int height){
if(x2 > x && x2 < x + width -1 && y2 > y && y2 < y + height -1){
return true;
}
return false;
}
这确实会运行,但只有在x2和y2的角落在另一个对象内时才会检测到碰撞。
那么如何改进碰撞检测?
我在网上找到的这张图片应该可以检测到程序中的碰撞。
//西蒙
答案 0 :(得分:2)
如果他们是圈子,那么这里有一些伪代码:
if (Math.sqrt(Math.pow(bitmap1.centerX-bitmap2.centerX, 2) + Math.pow(bitmap1.centerY-bitmap2.centerY, 2))<=bitmap1.width)
return true;
else
return false;
因为你现在想要矩形(假设它们的大小不同):
if (Math.abs(bitmap1.centerX-bitmap2.centerX)<=(bitmap1.width+bitmap2.width)/2f
&& Math.abs(bitmap1.centerY-bitmap2.centerY)<=(bitmap1.height+bitmap2.height)/2f)
return true;
else
return false;
希望有所帮助!
答案 1 :(得分:1)
bool isIntersect(Rectangle a, Rectangle b){
return a.Left < b.Right && a.Top < b.Bottom &&
b.Left < a.Right && b.Top < a.Bottom;
}
bool isIntersect(Circle a, Circle b)
{
Vector<ClassWithLengthRadiusProp> vDistanceProp = a.Center - b.Center;
return vDistanceProp.Length < a.Radius + b.Radius;
}
bool isIntersect(Circle a, Circle b)
{
Vector<ClassWithLengthRadiusProp> vDistanceProp = a.Center - b.Center;
float radiusSum = a.Radius + b.Radius;
float squaredDistanceLength = vDistanceProp .x * vDistanceProp .x +
vDistanceProp .y * vDistanceProp .y;
return squaredDistanceLength < radiusSum * radiusSum;
}
答案 2 :(得分:0)
if(r1.lowerLeft.x < r2.lowerLeft.x + r2.width
&& r1.lowerLeft.x + r1.width > r2.lowerLeft.x
&& r1.lowerLeft.y < r2.lowerLeft.y + r2.height
&& r1.lowerLeft.y + r1.height > r2.lowerLeft.y)
return true;
else
return false;
除非您想要进行圆碰撞检测,否则应该这样做。 r1&amp; r2并定义为Rects
答案 3 :(得分:0)
android.graphics.Rect类包含一些很好的函数,可以在一行中完成。你可以看看相交。