python - How do I move a laser bullet in a top down shooter in a certain direction? -
i making game in pygame requires player defend earth aliens attacking it. player controlled arrow keys , spacebar used shoot. far working fine except lasers. when fire laser, wish them move in direction player facing.
here lazer
class:
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
so far laser moves when player presses arrow key. if player stops pressing arrow key, laser stop moving , if player moves in different direction, laser move in direction.
here full game code:
while gameon == true: player1.background(gamedisplay) if len(enemyaliens) < 1: pygame.time.delay(3000) wave = wave + 1 diff = diff + wave 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) 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) lazer1 in lazer_list: block_hit_list = pygame.sprite.spritecollide(lazer1, enemyaliens, true) 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) 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 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()
how can laser move in direction player moving, , not move along player?
Comments
Post a Comment