Reputation: 443
I am looking for a different way to create collision detection using Zelle Graphics and find_overlapping. I believe the overlapping shows where the bounding box of an object has come in contact with the bounding box of another object (the tuple)? I was hoping for some feedback on this code. Presently, the object goes through the rectangle before it breaks, but I think the idea has merit. This is just a test and need much more fine tuning.
from graphics import *
win = GraphWin("game loop", 500, 500, autoflush=False)
win.master.attributes('-topmost', True)
x=20
y=20
dx=20
play=0
cir1=Circle(Point(x,y),10)
cir1.setFill("red")
cir1.draw(win)
x1=300
x2=310
y1=0
y2=50
rect1=Rectangle(Point(x1,y1),Point(x2,y2))
rect1.setFill("blue")
rect1.draw(win)
xwidth=win.getWidth()
while play==0:
for i in range(100):
xposition = cir1.getCenter().getX()
test1=win.find_overlapping(x1,y1,x2,y2)
print("This is the length of test1:",len(test1))
print(test1)
if xposition+1>=xwidth or xposition-1<=0:
dx=-dx
cir1.move(dx, 0)
update(15)
if len(test1)==2:
print("overlap")
play=1
break
print("game over")
win.mainloop()
Upvotes: 0
Views: 262
Reputation: 142651
I see few problems:
you first check collision, next you move to new position, and next you check if to stop game - but you should stop game after checking collision without moving to new position. OR you should first move to new position, next check collision and check if to stop game.
you move dx = 20
but wall has width only 10
and it can jump it - you should use smaller dx
and use bigger value in update()
you check if wall overlaps any other objects but if you will have many walls then it would be simpler to check if circle overlaps any other objects.
when circle overlap then you would have to move it back - if you move right then you should set circle's right border in place of rectangle' left border.
Minimal working example with changes 1, 2, 3 but without 4 because it would need more changes.
from graphics import *
win = GraphWin("game loop", 500, 500, autoflush=False)
win.master.attributes('-topmost', True)
x = 200
y = 20
dx = -5
play = True
cirle = Circle(Point(x, y), 10)
cirle.setFill("red")
cirle.draw(win)
x1 = 300
x2 = 310
y1 = 0
y2 = 50
rect1 = Rectangle(Point(x1, y1), Point(x2, y2))
rect1.setFill("blue")
rect1.draw(win)
xwidth = win.getWidth()
while play:
for i in range(100):
# move circle to new position
cirle.move(dx, 0)
# get circle's new position
p1 = cirle.getP1()
p2 = cirle.getP2()
# check circle's collision in new position
overlaps = win.find_overlapping(p1.x, p1.y, p2.x, p2.y)
print("test:", len(overlaps), overlaps)
if len(overlaps) > 1:
print("overlap")
play = False
break
# check circle's collision with window's boders
if p2.x >= xwidth or p1.x <= 0:
dx = -dx
update(50)
print("game over")
#win.mainloop() # no need if you use `update()`
Upvotes: 1