How do I implement collision detection?

后端 未结 2 676
清歌不尽
清歌不尽 2021-01-29 11:53
from graphics import*
import time
import random 

def main():

    numx=random.randint(10,700)

    wn=GraphWin(\"AK\",700,700)
    wn.setBackground(\"white\")

    msg=         


        
相关标签:
2条回答
  • 2021-01-29 12:04

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

    0 讨论(0)
  • 2021-01-29 12:06

    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.

    0 讨论(0)
提交回复
热议问题