问题时,矩形碰撞在pygame



我想做一个简单的游戏,但我卡住了,因为当两个矩形碰撞时,生命应该一个接一个地下降,我很确定这是因为像素,但我仍然不知道如何修复它。我应该改变碰撞方法吗?

player_img = pygame.image.load('umbrella.png')
p_img = pygame.transform.scale(player_img, (128, 128))
px = 330
py = 430
px_change = 0
r1 = p_img.get_rect()

raio_img = pygame.image.load('untitleddesign_1_original-192.png')
r_img = pygame.transform.scale(raio_img, (40, 60))
rx = 335
ry = 50
r_direcao = 3
r_counter = 0
raio_velocidade = 6
r2 = r_img.get_rect()

def raio(x, y):
game_screen.blit(r_img, (r2))

def player(x, y):
x = 330
y = 430
game_screen.blit(p_img, (r1.x, r1.y))

life = 0 
f = pygame.font.Font('dogica.ttf', 16)
fx = 5
fy = 5
def font(x, y):
s = f.render("life : " + str(life), True, (0, 0, 0))
game_screen.blit(s, (x, y))

for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
colision = r2.colliderect(r1) 
if colision:
life -= 1  # here when i collide the two rects the life goes down by 31 instead of going by one.


只要矩形发生碰撞,碰撞就会被识别。因此,在连续的帧中,只要矩形发生碰撞,"寿命"就会减少。

添加一个变量,指示矩形是否在前一帧中碰撞。当矩形碰撞时,不要减少'寿命':

collided_in_previous_frame = False
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# [...]
colision = r2.colliderect(r1) 
if colision and not collided_in_previous_frame:
life -= 1
collided_in_previous_frame = colision 
# [...]

最新更新