矩形在 pygame 中发生碰撞时出现问题
problem when rectangles collide in 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.
只要矩形碰撞就可以识别碰撞。因此,只要矩形发生碰撞,'life' 就会在连续帧中递减。
添加一个变量,指示矩形是否在前一帧发生碰撞。不要在矩形碰撞时减少 'life':
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
# [...]
我正在尝试制作一个简单的游戏,但我被卡住了,因为当两个矩形碰撞时,生命应该一个接一个地下降,我很确定这是因为像素,但我仍然不不知道如何修复它。我应该更改碰撞方法吗?
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.
只要矩形碰撞就可以识别碰撞。因此,只要矩形发生碰撞,'life' 就会在连续帧中递减。
添加一个变量,指示矩形是否在前一帧发生碰撞。不要在矩形碰撞时减少 'life':
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
# [...]