How do I implement collision detection?

2019-03-07 10:28发布

问题:

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,30),"Score")
    msg.setSize(12)
    msg.setTextColor('blue')
    msg.draw(wn)

    inch=Entry(Point(60,30),2)
    inch.setFill('white')
    inch.draw(wn) 

    sqrg=Rectangle(Point(330,650),Point(430,665))
    sqrg.setFill("red")
    sqrg.draw(wn)

    blx=Circle(Point(numx,80),20)
    blx.setFill("blue")
    blx.draw(wn)


    xval=10
    yval=0
    wn.getMouse()
    for i in range(150):
        sqrg.move(xval,yval)
        symbl=wn.checkKey()
        if symbl=="Right":
                xval=10
                yval=0
        if symbl=="Left":
                xval=-10
                yval=0
        time.sleep(0.08)
        blx.move(0,20)

main()

I'm very confused my professor is very confusing, and I need to do this for a project where when collision is detected the score goes up.

回答1:

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



回答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.