How do I implement collision detection?

﹥>﹥吖頭↗ 提交于 2019-12-02 13:24:27

Your radius is twenty. Inside the loop, just test whether Euclidean distance between sqrg and blx is within 20.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!