两个物体之间的距离

时间:2012-11-04 20:00:36

标签: python canvas tkinter

所以我一直试图弄清楚如何在画布上找到两个物体之间的距离,而我已经用尽了谷歌上最相关的链接,但收效甚微。

我正在努力使它计算绘制的椭圆与画布上的线之间的距离。

from __future__ import division
from Tkinter import *
import tkMessageBox

class MyApp(object):
    def __init__(self):
        self.root = Tk()
        self.root.wm_title("Escape")
        self.canvas = Canvas(self.root, width=800, height=800, bg='white')
        self.canvas.pack()
        self.canvas.create_line(100, 100, 200, 200, fill='black')
        self.canvas.bind("<B1-Motion>", self.tracer)
        self.root.mainloop()

    def tracer(self, e):
        self.canvas.create_oval(e.x-5, e.y-5, e.x+5, e.y+5, fill='blue', outline='blue')
        rx = "%d" % (e.x)
        ry = "%d" % (e.y)
        print rx, ry
MyApp()

2 个答案:

答案 0 :(得分:1)

两个圈子:

dist = math.sqrt((circle1.x-circle2.x)**2 + (circle1.y-circle2.y)**2) - circle1.r - circle2.r

有点显而易见,他们的欧几里德距离是用毕达哥拉斯定理计算的。

点/段:

 a = segment[1].y - segment[0].y
 b = segment[0].x - segment[1].x
 c = - segment[0].x * a - segment[0].y * b 
 dx = segment[1].x - segment[0].x
 dy = segment[1].y - segment[0].y
 nc0 = - segment[0].x * dx - segment[0].y * dy
 nc1 = - segment[1].x * dx - segment[1].y * dy
 if ((dx * x + dy * y + nc0) < 0) dist = math.sqrt((x-segment[0].x)**2 + (y-segment[0].y)**2)
 elif((dx * x + dy * y + nc1) < 0) dist = math.sqrt((x-segment[1].x)**2 + (y-segment[1].y)**2)
 else dist = (a*x + b*y + c) / math.sqrt(a**2 + b**2)

圆/段 - 与点/段相同,只是减去圆的半径

多边形/多边形 - 遍历多边形1的每个顶点和多边形2的线段,然后遍历多边形2的每个顶点和多边形1的线段,然后找到最小的。

不要在代码中使用幻数。半径为5并不好。

答案 1 :(得分:0)

dist = math.sqrt((oval.x-point.x)**2 + (oval.y-point.y)**2)

不确定这是否能回答你的问题,但这是距离公式

原始问题存在一些问题。

  1. 你想在什么时候找到距离?

  2. 你没有保存椭圆形位置所以以后很难查找

  3. 你为什么试图找到距离?/你打算用它做什么?

  4. 您是想找到距边缘的距离还是距离中心的距离?

  5. 一般来说,我猜你想在def trace函数

    中得到它

    步骤1.兴趣点是(e.x,e.y

    步骤2.找到该行上最近的点(line =(100,100)to(200,200))(这可能是一个问题。http://nic-gamedev.blogspot.com/2011/11/using-vector-mathematics-and-bit-of_08.html

    步骤3.将距离法应用于兴趣点和最近点线

    def dist(pt1,pt2):
        return ((pt1.x-pt2.x)**2 + (pt1.y-pt2.y)**2)**.5
    

    在另一边注意......你的椭圆看起来像圈子一样......