Python - Balls作为同一个对象的实例互相反弹

时间:2017-11-17 12:52:55

标签: python python-3.x tkinter collision-detection

Python - 球作为同一个对象的一部分互相反弹

我试图制作一个程序,其中多个球沿不同方向的数字线移动。程序的目的是让球在彼此碰撞或与数字线的末端碰撞时改变方向。我使用一个物体制作了多个球,并使它们各自都有自己的颜色和方向(速度对所有人来说都是一样的)。我现在卡在检测球何时与另一个球碰撞并让他们改变方向时。如果它们是同一物体的一部分,我如何检测碰撞?是否可能?谢谢你的帮助!

    from tkinter import *
import time

tk = Tk()    

canvas = Canvas(tk, width=2200, height=600)
tk.title("Balls")
canvas.pack()

def base():
    canvas.create_line(50,400,2050,400)# number line
    for i in range(101):
        canvas.create_line(50+(i*20), 400, 50+(i*20), 390) # number ticks
        canvas.create_text(50+(i*20), 410, fill="darkblue", font="Times 8 italic bold", text=i) # the actual numbers
base()

class Ball:
    def __init__(self, start, color, direction):
        self.shape = canvas.create_oval((start*20) + 40, 390,(start*20) + 60, 370, fill=color)
        self.x = 20*direction
        self.y = 0

    def move(self):
        canvas.move(self.shape, self.x, self.y)
        pos = canvas.coords(self.shape) # pos = [left, top, right, bottom]
        if pos[2] >= 'another ball' or pos[0] <= 'another ball':   # idk how to make the balls detect each other here....
            self.x = -self.x            # delete the if statement and this line for program to work



colors = ['red','green','blue','orange','yellow','cyan','magenta',
          'turquoise','grey','gold','pink']
startPos = [24,52,60,84]
direction = [1,-1,1,-1]
balls = []

for i in range(4):
    balls.append(Ball(startPos[i],colors[i],direction[i]))


while True:
    for ball in balls:
        ball.move()
    tk.update()
    time.sleep(0.5)


tk.mainloop()

0 个答案:

没有答案