Python碰撞检测

时间:2015-01-29 18:41:14

标签: python pygame collision-detection

我在pygame中制作了一个游戏,我开始添加碰撞检测。对于两个精灵(鸭子和岩石),我给了他们一个矩形变量。我怎么知道检查它们是否发生碰撞? 这是代码:

import pygame, sys
from pygame.locals import *

pygame.init()

clock = pygame.time.Clock()

#screen constants
screen = pygame.display.set_mode((1050,350),0,32)
x = 0
screenWidth = 1050
speed = 2

#background constants
b1 = "bg1.jpg"
b2 = "bg2.jpg"
back = pygame.image.load(b1).convert()
back2 = pygame.image.load(b2).convert()

#duck constants
duck = pygame.image.load("duck.png")
rect_duck = duck.get_rect()
duckY = 246
duckMoveY=0
flying = False
falling = False

#rock constants
rock = pygame.image.load("rock.png")
rect_rock = rock.get_rect()
rockX = 0


#init game loop
while True:

    #check if they want to quit
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        #see if they fly
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                flying = True

        #see if they fall
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                falling = True
                flying = False

    #flying
    if flying == True:
        duckMoveY = -5

    #falling
    if falling == True:
        duckMoveY = 5

    #display the backgrounds
    screen.blit(back, (x,0))
    screen.blit(back2,(x-screenWidth,0))

    #display the duck
    screen.blit(duck, (500,duckY))

    #display the rock
    screen.blit(rock, (rockX, 275))   

    #move background
    x += speed
    if x == screenWidth:
        x = 0

    #move the duck
    duckY += duckMoveY

    #move the rock
    rockX += speed

    #stop them falling off the screen
    if duckY > 246:
        falling = False
        duckY = 246

    #stop them flying off the top
    if duckY < 0:
        flying = False
        duckY = 0



    #update the screen and set fps
    pygame.display.update()
    pygame.display.flip()
    msElapsed = clock.tick(100)

1 个答案:

答案 0 :(得分:0)

我建议你把这些变量变成圆形而不是矩形。然后,当两个中心之间的距离小于半径之和时,您将发生碰撞。

if(m.sqrt((duckX-rockX)**2+(duckY-rockY)**2)<=radius+cursorRadius):
   print("Collision!")