【发布时间】:2021-11-04 20:24:05
【问题描述】:
从事一个涉及 tkinter 的小项目,我需要弄清楚如何让球相互反弹。
代码如下:
from tkinter import *
# dimensions of canvas
WIDTH=300
HEIGHT=400
# Create window and canvas
window = Tk()
canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg='#ADF6BE')
canvas.pack()
# starting position of ball
x = 0
y = 10
# starting position of ball1
x1 = 100
y1 = 0
# distance moved each time step for ball 1
dx = 10
dy= 10
# distance moved each time step for ball 2
dx1 = 10
dy1 = 10
# diameter of ball
ballsize = 30
while True:
x = x + dx
y = y + dy
x1 = x1 + dx1
y1 = y1 + dy1
# if ball get to edge then we need to
# change direction of movement
if x >= WIDTH-ballsize or x <= 0 or x == x1:
dx = -dx
print("x=", x)
print('y=', y)
if y >= HEIGHT-ballsize or y <= 0 or y == y1:
dy = -dy
print("x=", x)
print('y=', y)
if x1 >= WIDTH-ballsize or x1 <= 0 or x1 == x:
dx1 = -dx1
print("x1=", x1)
print('y1=', y1)
if y1 >= HEIGHT-ballsize or y1 <= 0 or y1 == y:
dy1 = -dy1
print("x1=", x1)
print('y1=', y1)
# Create balls
ball=canvas.create_oval(x, y, x+ballsize, y+ballsize, fill="white", outline='white')
ball1 = canvas.create_oval(x1, y1, x1 + ballsize, y1 + ballsize, fill="white", outline='white')
# display ball
canvas.update()
canvas.after(50)
#remove ball
canvas.delete(ball)
canvas.delete(ball1)
window.mainloop()
它们在画布墙壁上移动并反弹,但不会相互反弹。
这里有一张图片来说明我的意思,而不是互相撞击并弹开
【问题讨论】:
-
我看到了你检测墙壁的代码,但没有看到任何检测其他球的代码。只需在同一个地方添加即可。我还建议您更新球的位置,或者删除并重新制作每一帧的球(这将有助于它更顺畅地运行)。
-
计算两个球中心之间的
distance,如果distance <= ballsize,则两个球相撞。
标签: python user-interface tkinter canvas