如何检查tkinter中的两个球是否碰撞?

2024-10-08 23:28:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我和特金特正在做一个小项目,我需要弄清楚如何让球从对方身上弹下来

代码如下:

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()

它们会从帆布墙上移动和反弹,但不会彼此分开

这里有一张图片来展示我的意思,而不是互相撞击和弹跳

Balls not colliding


Tags: orofifwindowwidthcanvasprintx1
1条回答
网友
1楼 · 发布于 2024-10-08 23:28:19

你必须检查球之间的距离。 如果两个圆的中心之间的距离小于两个圆半径之和,则它们发生碰撞

(math.sqrt((ball1.x- ball2.x) ** 2 + (ball1.y - ball2.y) ** 2) <= sum_radii

然后改变球的dy和dx

相关问题 更多 >

    热门问题