如何确定tkinter多边形是否发生碰撞?

时间:2014-12-22 16:02:49

标签: python tkinter collision-detection

到目前为止,这是我的代码:

from tkinter import *
import winsound
tk = Tk()

def key(event):
    inp = '' + event.char
    if inp == 'w':
        canvas.move(p1,0,-5)
        winsound.Beep(1000,50)
    if inp == 's':
        canvas.move(p1,0,5)
        winsound.Beep(1000,50)
    if inp == 'a':
        canvas.move(p1,-5,0)
        winsound.Beep(1000,50)
    if inp == 'd':
        canvas.move(p1,5,0)
        winsound.Beep(1000,50)

    if inp == 'i':
        canvas.move(p2,0,-5)
        winsound.Beep(700,50)
    if inp == 'k':
        canvas.move(p2,0,5)
        winsound.Beep(700,50)
    if inp == 'j':
        canvas.move(p2,-5,0)
        winsound.Beep(700,50)
    if inp == 'l':
        canvas.move(p2,5,0)
        winsound.Beep(700,50)

def callback(event):
    canvas.focus_set()



canvas = Canvas(tk, width=600, height=600)
canvas.bind("<Key>", key)
canvas.bind("<Button-1>", callback)
canvas.pack()
p1 = canvas.create_polygon(10,10,20,10,15,0,fill='red')
p2 = canvas.create_polygon(510,10,520,10,515,0,fill='blue')
tk.update()


tk.mainloop()

我想检查多边形是否相互碰撞并发送&#34;游戏结束&#34;发生这种情况时的消息 所以当碰撞时我会print('you lost'),但我不知道如何检查碰撞。

1 个答案:

答案 0 :(得分:1)

画布有一个find_overlapping方法,它将返回与矩形区域重叠的所有项目。您可以使用bbox方法获取给定玩家的直角坐标。如果你有非矩形物体,碰撞检测不会100%精确,但它可能足够接近。