我正在Pygame制作一款游戏,要求玩家从攻击它的外星人身上捍卫地球。使用箭头键控制播放器,并使用空格键进行拍摄。到目前为止,除激光器外,一切工作正常。当我发射激光时,我希望它们朝着玩家面向的方向移动。
这是我的lazer
课程:
class lazer(pygame.sprite.Sprite):
def __init__(self):
super(lazer, self).__init__()
self.image = pygame.image.load('lazer.png')
self.rect = self.image.get_rect()
def update1(self):
keyy = pygame.key.get_pressed()
speed = 30
if keyy[pygame.K_UP]:
self.rect.y -= speed
elif keyy[pygame.K_DOWN]:
self.rect.y += speed
if keyy[pygame.K_RIGHT]:
self.rect.x += speed
elif keyy[pygame.K_LEFT]:
self.rect.x -= speed
到目前为止,只有当玩家按下箭头键时激光才会移动。如果玩家停止按箭头键,激光器也将停止移动,如果玩家向不同方向移动,激光器也会朝那个方向移动。
这是我的完整游戏代码:
while GameOn == True:
Player1.background(gameDisplay)
if len(EnemyAliens) < 1:
pygame.time.delay(3000)
wave = wave + 1
diff = diff + wave
for i in range(diff):
block = Aliens()
block.rect.y = random.randrange(200, DisplayHeight-10)
block.rect.x = random.randrange(110, DisplayWidth-10)
EnemyAliens.add(block)
all_sprites.add(block)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
keyy = pygame.key.get_pressed()
print(direction)
lazer1 = lazer()
lazer1.rect.y = Player1.rect.y
lazer1.rect.x = Player1.rect.x
all_sprites.add(lazer1)
lazer_list.add(lazer1)
for lazer1 in lazer_list:
block_hit_list = pygame.sprite.spritecollide(lazer1, EnemyAliens, True)
for block in block_hit_list:
lazer_list.remove(lazer1)
all_sprites.remove(lazer1)
score += 1
print(score)
if lazer1.rect.y<-10 or lazer1.rect.y > DisplayHeight + 10 or lazer1.rect.x < -10 or lazer1.rect.x > DisplayWidth +10:
lazer_list.remove(lazer1)
all_sprites.remove(lazer1)
for block in EnemyAliens:
speed = 3
if block.rect.x > 115:
block.rect.x -= speed
elif block.rect.x < 115:
block.rect.x += speed
if block.rect.y < 91:
block.rect.y += speed
elif block.rect.y > 91:
block.rect.y -= speed
col = pygame.sprite.collide_rect(Earth1,block)
if col == True:
all_sprites.remove(block)
EnemyAliens.remove(block)
earth_health -= 10
for Pl in PlayerList:
key = pygame.key.get_pressed()
speed = 6
direction = "w"
if key[pygame.K_UP]:
Pl.rect.y -= speed
direction = "U"
elif key[pygame.K_DOWN]:
Pl.rect.y += speed
direction = "D"
if key[pygame.K_RIGHT]:
Pl.rect.x += speed
direction = "R"
elif key[pygame.K_LEFT]:
Pl.rect.x -= speed
direction = "L"
if earth_health == 0 or earth_health < 0:
if score > Highscore:
saveHs(score)
GameOn = False
HealthBars(earth_health)
all_sprites.update()
all_sprites.draw(gameDisplay)
PlayerList.draw(gameDisplay)
pygame.display.update()
如何让激光沿着玩家移动的方向移动,而不是随着玩家一起移动?