C++计算两个圆之间的距离
C++ calculate the distance between two circles
有人可以解释一下吗?
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.x
,Circle.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)
这就是原因。
相关文章:
- 用C++程序计算圆锥体的体积、球体的体积、八边形的面积和两点之间的距离
- 计算所有对之间的曼哈顿距离
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 两个有符号数字之间的距离
- 计算车辆之间的距离并设置速度,使距离保持不变,例如 5 米
- 计算两个迭代器之间的距离时"Vector Iterators Incompatible"
- 查找彼此之间具有不同最小距离的随机数
- 相同字符之间的最小距离
- 如何排列二进制字符串以最小化它们之间的距离
- 堆和堆栈之间的距离
- 树节点之间的最大距离中的运行时错误
- 最接近的字符串:在字符串阵列中找到2个字符串之间的最小距离
- 尝试查找数组中点之间的最小距离时的随机垃圾输出
- c++ 从大型数组中读取 3D 坐标并计算它们之间的距离
- 在 OpenCV 中计算 SURF 功能之间的距离
- 计算机如何分配两个变量,我们如何计算两个变量之间的距离?
- 是否有C 功能来计算两个索引之间的距离
- 使用 DirectXMath 获得 2 点之间距离的最佳方法是什么
- <random> 点之间距离最小的uniform_real_distribution
- 确定景观中所有点与具有特定属性的点之间距离的最快方法