0

Here I have made a code to create random sized bubbles which can be destroyed by collision of another object:

import tkinter
window = tkinter.Tk()
window.title("...")
c = tkinter.Canvas(width=800, height=500, bg="...")
ojct_id1 = c.create_polygon(...)
ojct_id2 = c.create_oval(...)           # A polygon in an oval should constitute the object
def move ojct(event):
    ...
from random import randint
bubbles = list()
bubbles_r = list()                    # radius
bubbles_speed = list()
def create_bub():
    ...
def move_bubbles():
    ...
from time import sleep
while True:
    if randint(1, 10) == 1:
        create_bub()
    move_bubbles()
    window.update()
    sleep(0.01)

The following code determines the position of any bubble:That helps to find out collision.

def hole_coord(id_num):
    pos = c.coords(id_num)
    x = (pos[0] + pos[2])/2
    y = (pos[1] + pos[3])/2
    return x, y 

Now I have to make func. for deleting bubbles:

def del_bubbles():
    del bubbles_r[i]
    del bubbles_speed[i]
    c.delete(bubbles[i])
    del bubbles[i]

The following code determines, if the two objects are colliding:

from math import sqrt
def distance(id1, id2):
    x1, y1 = hole_coord(id1)
    x2, y2 = hole_coord(id2)
    return sqrt((x2 - x1)/2 + (y2 - y1)/2)
def collision():
    for bub in range(len(bubbles)-1, -1, -1):
        if distance(ojct_id2, bubbles[bub]) < (15 + bubbles_r[bub]):
            del_bubbles(bub)

Here it is sth. wrong: bubbles get deleted without a hit but if they are hit often they don't get deleted. Can anybody help me? Thanks!

2
  • 2
    I think your distance function is wrong, it should be return sqrt((x1-x2)**2+(y1-y2)**2) Commented Jul 3, 2018 at 14:35
  • Thank you pLOPeGG! Commented Jul 4, 2018 at 12:23

1 Answer 1

4

You are not computing the euclidean distance correctly.

def distance(id1, id2):
    x1, y1 = hole_coord(id1)
    x2, y2 = hole_coord(id2)
    return sqrt((x2 - x1)/2 + (y2 - y1)/2)   # <----- this is wrong

should be

def distance(id1, id2):
    x1, y1 = hole_coord(id1)
    x2, y2 = hole_coord(id2)
    return sqrt((x2 - x1)**2 + (y2 - y1)**2)   # <----- square instead of halve
Sign up to request clarification or add additional context in comments.

2 Comments

Well, thank you kutschkem, I'm bad at math, you know :-D
@Timmy Don't believe that. ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.