问题描述
所以我正在尝试检查我的鸟类图像是否接触了我的图像,以及它们是否要打印 print('Collided1!')
。
我的问题是 print('Collided1!')
无论如何都会消失,并且不检查图像是否接触。 colliderect 是我在网上找到的解决方案,但我似乎不知道它是如何工作的,因为它不起作用。
你知道如何解决这个问题吗?并检查我的图像是否触动?
from random import randint
import pygame,sys
import random
import time
pygame.init()
pygame.display.set_caption('Lokaverkefni')
disPLAYSURF = pygame.display.set_mode((1224,724))
fpsClock = pygame.time.Clock()
FPS = 60
a = 1
b = 1
c = 15
x = 100
y = 480
start = 0
score = 0
landX = 1205
totalscore = 0
level = 'low'
directionForBird = 'none'
WHITE = (255,255,255)
BLACK = (0,0)
BASICFONT = pygame.font.Font('freesansbold.ttf',30)
background_resized = pygame.image.load('sky.jpg')
background = pygame.transform.scale(background_resized,(1224,724))
bird1 = pygame.image.load('bird1.png')
bird1_resized = pygame.transform.scale(bird1,(170,150))
bird1Surface = bird1_resized.get_rect()
bird2 = pygame.image.load('bird2.png')
bird2_resized = pygame.transform.scale(bird2,150))
bird2Surface = bird2_resized.get_rect()
cloudsList = ['cloud1.png','cloud2.png','cloud3.png','cloud4.png']
clouds = random.choice(cloudsList)
cloud = pygame.image.load(clouds)
cloud_resized = pygame.transform.scale(cloud,(352,352))
cloudSurface = cloud_resized.get_rect()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if level == 'low':
if (event.key == K_SPACE ):
directionForBird = 'up'
level = 'high'
FPS += 2
c += 1
if directionForBird == 'up':
y -= 10
if y == 10:
directionForBird = 'down'
if directionForBird == 'down':
y += 10
if y == 480:
directionForBird = 'none'
if a == 1:
disPLAYSURF.blit(background,(0,0))
disPLAYSURF.blit(bird1_resized,(x,y))
disPLAYSURF.blit(cloud_resized,(landX,300))
b += 1
if b == c:
a += 1
if a == 2:
disPLAYSURF.blit(background,0))
disPLAYSURF.blit(bird2_resized,300))
b -= 1
if b == 1:
a -= 1
start += 1
if start == 100:
start -= 1
directionForLand = 'left'
if directionForLand == 'left':
landX -= 15
if landX == -550:
landX = 1205
level = 'low'
clouds = random.choice(cloudsList)
cloud = pygame.image.load(clouds)
cloud_resized = pygame.transform.scale(cloud,352))
score += 1
if score == 30:
score = 0
totalscore += 1
scoreText = BASICFONT.render('Stig : %s' % (totalscore),True,(BLACK))
scoreRect = scoreText.get_rect()
scoreRect.topleft = (1070,10)
disPLAYSURF.blit(scoreText,scoreRect)
# This is Supossed to Be what checks if the bird images
# colide with the cloud images
if bird1Surface.colliderect(cloudSurface):
print('Collided1!')
if bird2Surface.colliderect(cloudSurface):
print('Collided1!')
pygame.display.update()
fpsClock.tick(FPS)
解决方法
bird1Surface
、bird2Surface
和 cloudSurface
的左上角始终为 (0,0),因此它们始终位于彼此的顶部。您无需更改矩形当你移动鸟。在进行碰撞检查之前,您需要跟踪鸟的 x,y 和云的 x,y,并使用当前的 x,y 和已知的宽度和高度构造新的矩形。