0

有人可以解释一下吗?

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

4

5 回答 5

6

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

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

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

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

于 2012-09-21T18:41:43.757 回答
3

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

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

于 2012-09-21T18:39:53.683 回答
2

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

d = (x2 + y2)(1/2)

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

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

于 2012-09-21T18:39:36.943 回答
1

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

于 2012-09-21T18:40:17.147 回答
1

两点的距离可以通过使用 Pithagroas 关于直角三角形的定理来推断。在笛卡尔坐标系中,如果定义两个点: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。因此 Pithagoras 定理适用于:

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)

这就是为什么。

于 2012-09-21T18:48:47.447 回答