gpt4 book ai didi

python - Pygame碰撞检测问题

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:53 24 4
gpt4 key购买 nike

我正在用 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()

你能告诉我我的代码有什么问题吗?

最佳答案

我建议创建两个pygame.Rect,一个用于玩家,一个用于敌人。然后通过增加矩形的 y 属性来移动敌人,并使用 colliderect 方法查看两个矩形是否发生碰撞。

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()

关于python - Pygame碰撞检测问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49396828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com