且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

接触检测算法

更新时间:2023-02-26 16:29:11

尝试使用 Rectangle.Intersect 方法 [ ^ ]。


好吧,如果你想检测两个之间的碰撞,那么条件应该是(经谢尔盖的批准:-D)。

Well, if you want to detect collision between two balls then the condition should be (subject to Sergey''s approval :-D).
(XC0-XC1)*(XC0-XC1)+(YC0-YC1)*(YC0-YC1) <= R1*R1+R2*R2+2*R1*R2





这两个中心之间的距离小于(或等于)它们的半径之和



That is distance between the two centers is less than (or equal) to sum of their radii


我认为***的解决方案结合了上面的两条评论,看起来应该是这样的:



I think the best solution combines both comments above, and should look something like this:

if( ! Ball1.IntersectsWith(Ball2))
{
   return false;
}

double Ball1CenterX = (Ball1.Right - Ball1.Width)/2;
double Ball2CenterX = (Ball2.Right - Ball2.Width)/2;
double Ball1CenterY = (Ball1.Bottom - Ball1.Height)/2;
//double Ball2CenterY = (Ball1.Bottom - Ball1.Height)/2;    // oops! (Ball1 ?) [MTH: fixed below]
double Ball2CenterY = (Ball2.Bottom - Ball2.Height)/2;

double Ball1Radious = Ball1.Width/2;
double Ball2Radious = Ball2.Width/2;

return (Ball2CenterX - Ball1CenterX)^2 + (Ball2CenterY - Ball1CenterY)^2 
         <= 
        (Ball1Radious + Ball2Radious)^2;   // [MTH: fixed. don't "times 2"]