我有一个游戏,用户可以使用箭头键移动玩家(“mrhinckleberg”)。还有两个敌人"它会自动上下跳动。
我现在如何检测玩家与敌人之间的碰撞?
这是我到目前为止的代码:
import pygame
import time
pygame.init()
window = pygame.display.set_mode((800,800))
pygame.display.set_caption("Yues")
theboard = pygame.image.load('theboard.png')
enemy = pygame.image.load('mrenemy.png')
mrhinckleberg = pygame.image.load('MrHinckleBerg.png')
mrhincklebergdead = pygame.image.load('MrHinckleBergdead.png')
deathscreen = pygame.image.load('deathscreen.png')
black = (0,0,0)
clock1 = pygame.time.Clock()
def quitt():
pygame.quit()
quit()
playerx = 750
playery = 450
enemydirection = 'down'
enemyx = 500
enemyy = 50
enemyspeed = 100
enemydirection2 = 'up'
enemyx2 = 350
enemyy2 = 750
enemyspeed2 = 50
enemydirection3 = 'down'
enemyx3 = 200
enemyy3 = 50
enemyspeed3 = 150
while True:
window.blit(theboard, (0,0))
if enemydirection == 'down':
enemyy += enemyspeed
if enemyy >= 790:
enemydirection = 'up'
elif enemydirection == 'up':
enemyy -= enemyspeed
if enemyy <= 10:
enemydirection = 'down'
if enemydirection2 == 'up':
enemyy2 -= enemyspeed2
if enemyy2 <= 10:
enemydirection2 = 'down'
elif enemydirection2 == 'down':
enemyy2 += enemyspeed2
if enemyy2 >= 790:
enemydirection2 = 'up'
for event in pygame.event.get():
if event.type == pygame.QUIT:
quitt()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
playerx += 12
elif event.key == pygame.K_LEFT:
playerx -= 12
elif event.key == pygame.K_UP:
playery -= 12
elif event.key == pygame.K_DOWN:
playery += 12
if playerx == enemyx and playery == enemyy:
print("hai")
window.blit(theboard, (0,0))
window.blit(mrhinckleberg, (playerx,playery))
window.blit(enemy, (enemyx,enemyy))
window.blit(enemy, (enemyx2,enemyy2))
window.blit(enemy, (enemyx3,enemyy3))
pygame.display.update()
答案 0 :(得分:0)
在我的观点中,问题是您检查变量playerx
是否等于到enemyx
,但是由于您更改了{{1},这将永远不会成立仅在特定间隔中添加变量(加或减12)。
要避免这种情况,您可以检查enemyx
/ playerx
和playery
/ enemyx
是否在某个范围内**:
enemyy
请注意,Python中的比较可以链接。这意味着if (playerx <= enemyx <= playerx + playerWidth) and \
(playery <= enemyy <= playery + playerHeight):
print("hai")
相当于5 < x <= 10
。有关详细信息,请参阅Built-in Types -> Comparisons。
更新的代码:
5 < x and x <= 10
我希望这会有所帮助:)