Home > Back-end >  How do I check if two balls collide in tkinter?
How do I check if two balls collide in tkinter?

Time:09-17

Working on a small project involving tkinter and I need to figure out how to get balls bouncing off of each other.

Heres the code:

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

They move and bounce off of the canvas walls but not off of each other.

Heres an image to show what I mean, instead of hitting each other and bouncing off

Balls not colliding

CodePudding user response:

You have to check the distance between the balls. If the distance between the center of the two circles is less than the sum of the radii of the circles, then they are colliding.

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

Then change the dy and dx of the balls.

  • Related