我正在用pygame制作游戏,你必须躲避坠落的物体。我在碰撞检测方面遇到了麻烦,因为当障碍物接触到玩家时,它只会穿过底部。这是我的代码。
pygame.K_LEFT:
p_x_change = 0
screen.fill(WHITE)
pygame.draw.rect(screen,BLUE,(p_x,p_y, 60, 60))
pygame.draw.rect(screen,RED,(e_x,e_y,100,100))
p_x += p_x_change
e_y += e_ychange
if e_y > display_height:
e_y = 0
e_x = random.randint(1,display_width)
#Collision detection below
elif e_y == p_y - 90 and e_x == p_x :
done = True
clock.tick(60)
pygame.display.update()
你能告诉我我的代码有什么问题吗?
答案 0 :(得分:1)
我建议创建两个pygame.Rect
,一个用于玩家,一个用于敌人。然后通过增加rect的y
属性来移动敌人,并使用colliderect
方法查看两个rect是否发生碰撞。
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
display_width, display_height = screen.get_size()
clock = pygame.time.Clock()
BG_COLOR = pygame.Color('gray12')
BLUE = pygame.Color('dodgerblue1')
RED = pygame.Color('firebrick1')
# Create two rects (x, y, width, height).
player = pygame.Rect(200, 400, 60, 60)
enemy = pygame.Rect(200, 10, 100, 100)
e_ychange = 2
done = False
while not done:
# Event handling.
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
player.x -= 5
elif keys[pygame.K_d]:
player.x += 5
# Game logic.
enemy.y += e_ychange # Move the enemy.
if enemy.y > display_height:
enemy.y = 0
enemy.x = random.randint(1, display_width)
# Use the colliderect method for the collision detection.
elif player.colliderect(enemy):
print('collision')
# Drawing.
screen.fill(BG_COLOR)
pygame.draw.rect(screen, BLUE, player)
pygame.draw.rect(screen, RED, enemy)
pygame.display.flip()
clock.tick(30)
pygame.quit()