C++计算两个圆之间的距离

C++ calculate the distance between two circles

本文关键字:之间 距离 两个 计算 C++      更新时间:2023-10-16

有人可以解释一下吗?

double distance( int x1, int y1, int x2, int y2 )
{
    //Return the distance between the two points
    return sqrt( pow( x2 - x1, 2 ) + pow( y2 - y1, 2 ) );
}
bool check_collision( Circle &A, Circle &B )
{
    //If the distance between the centers of the circles is less than the sum of their radii
    if( distance( A.x, A.y, B.x, B.y ) < ( A.r + B.r ) )
    {
        //The circles have collided
        return true;
    }
    //If not
    return false;
}

我不明白这段代码是怎么回事

//Return the distance between the two points
return sqrt( pow( x2 - x1, 2 ) + pow( y2 - y1, 2 ) );

返回两个圆之间的距离。代码来自 http://lazyfoo.net/SDL_tutorials/lesson19/index.php

sqrt( pow( x2 - x1, 2 ) + pow( y2 - y1, 2 ) )

返回圆心之间的欧氏距离。作为一个公式,这个距离很简单

sqrt((a1-b1)^2 + (a2-b2)^2)

其中 (a1,a2) 和 (b1,b2) 是 2 个圆的中心。

它不返回圆之间的距离,而是用普通的旧笛卡尔距离计算来执行它所说的"返回两点之间的距离"。然后程序员通过两个圆的中心

然后程序员减去两个半径以获得圆之间的距离。只是他没有真正费心去减去(s),他只是比较,因为他只对碰撞与不碰撞的决定感兴趣。

原点和点 (x, y) 之间的欧几里得距离由下式定义:

d = (x2 + y2)(1/2)
因此,两个圆的中心点 p 1 = (x 1, y

1 和 p 2 = (x 2, y2) 之间的距离是通过平移整个系统给出的,因此一个中心点位于原点,并计算到另一个中心点的距离。 我们通过以下方式做到这一点:

d = |p2 - p1|2
  = ((x2-x1)2 + (y2-y1)2)(1/2)

在C++,这通常看起来像

return sqrt( (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) );

然而,在这种情况下,看起来作者正在使用一个pow(b, e)函数,该函数采用第一个参数b,并将其提升到第二个参数的幂,e得到be

它返回圆心之间的距离。假设Circle.xCircle.y表示中心。这在其余的计算中用于检查碰撞。

两点的距离可以通过使用关于直角三角形的皮塔格罗斯定理来推断。在笛卡尔坐标系中,如果您定义两个点:P1(x1, y1) 和 P2(x2, y2),则它们之间将有一个直角三角形:

^ y
|
|
|
|
+ ---------x P1(x1, y1) = (12, 8)
|          |
|          | 
|          | 
+----------x-I-------x P2(x2, y2) = (24, 4)
|          |         |
|          |         |
|          |         |
+------------------------------------------------> x

现在P1, P2, I三角形在其点I处有一个直角。所以皮达哥拉斯定理适用于:

c ^ 2 = a ^ 2 + b ^ 2
distance ^ 2 = (x1 - x2) ^ + (y2 - y1) ^ 2
since n ^ 2 equals (-n) ^ 2 we can finally write:
distance = sqrt((x1 - x2) ^ 2 + (y1 - y2) ^ 2)

这就是原因。