How Do I Implement Collision Detection?
from graphics import* import time import random def main(): numx=random.randint(10,700) wn=GraphWin('AK',700,700) wn.setBackground('white') msg=Text(Point(25,3
Solution 1:
Your radius is twenty. Inside the loop, just test whether Euclidean distance between sqrg and blx is within 20.
Solution 2:
Below is a stripped down example based on your code. It measures the distance between the centers of the two moving objects to determine if a collision has occurred. If you manage to get the ball to hit the square, the ball should bounce straight up:
from random import randint
from time import sleep
from graphics import *
def distance(p1, p2):
return ((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2) ** 0.5
wn = GraphWin("AK", 700, 700)
sqrg = Rectangle(Point(325, 625), Point(375, 675))
sqrg.setFill("red")
sqrg.draw(wn)
numx = randint(10, 700)
blx = Circle(Point(numx, 80), 20)
blx.setFill("blue")
blx.draw(wn)
xval, yval = 10, 0
bheading = 1
wn.getMouse()
for i in range(150):
sqrg.move(xval, yval)
if distance(blx.getCenter(), sqrg.getCenter()) < 25:
bheading *= -1
symbl = wn.checkKey()
if symbl == "Right":
xval = 10
elif symbl == "Left":
xval = -10
sleep(0.1)
blx.move(0, bheading * 20)
Cleary not a viable game as-is, but a demonstration of collision detection.
Post a Comment for "How Do I Implement Collision Detection?"