pygame碰撞检测问题

贾山

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

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

r

我建议创建两个pygame.RectS,一个给玩家,一个给敌人。然后通过增加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()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章