Python冲突d

2024-07-07 01:39:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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)

Tags: theimageeventfalsetrueifdisplayscreen
1条回答
网友
1楼 · 发布于 2024-07-07 01:39:49

我建议你把这些变量做成一个圆而不是矩形。当两个中心之间的距离小于半径之和时,就会发生碰撞。你知道吗

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

相关问题 更多 >