0

所以我有一个随机的二维圆的中心点坐标数组,半径为 r。我需要创建一个函数来确定给定圆是否与另一个圆重叠。显然,如果它们在任一维度上的间隔小于 2r,它们就会重叠。我创建了一个函数来执行此操作:

          def x_overlap(n,r):
              radius_arr=array([2*r,2*r,2*r,2*r,2*r,2*r,2*r,2*r,2*r,2*r])
              diff_in_x=x-x[n]
              x_touch=radius_arr-diff_in_x
              for item in x_touch:
                  if item<0:
                      return "disk of ” n “ index overlaps with disk of ” x_touch.index(item) “ index in x direction"
                  else:
                      return "no overlaps for disk of ” n “ index in x direction"

          def y_overlap(n,r):
              radius_arr=array([2*r,2*r,2*r,2*r,2*r,2*r,2*r,2*r,2*r,2*r])
              diff_in_y=y-y[n]
              y_touch=radius_arr-diff_in_y
              for item in y_touch:
                  if item<0:
                      return "disk of “ n “ index overlaps with disk of ” y_touch.index(item) “ index in y direction"
                  else:
                      return "no overlaps for disk of “ n “ index in y direction"
          def overlap(n,r):
              return x_overlap(n,r) + " " + "and" + " " + y_overlap(n,r)

这段代码我遇到了一些问题;首先,它很长。其次,当我运行该函数时,n's 和 y_touch.index(item) 引用不会出现在控制台中。我的代码有什么问题,有更好的方法吗?

谢谢!

4

1 回答 1

4

检查中心点之间的距离是否小于半径之和:

def is_overlap(circle1, circle2):
    distance = ((circle1.x - circle2.x)**2 + (circle1.y - circle2.y)**2)**0.5

    return distance < circle1.r + circle2.r

您的代码不适用于像这样定位的圆圈(您的代码确实将圆圈视为正方形):

 o
o
于 2012-12-29T17:58:12.160 回答