简体   繁体   中英

Pygame how to set a certain delay on automatic shooting

I'm trying to create a space shooting game the problem is I need to set a certain delay in the game loop so that the shooting can be controlled. If possible if the delay can be stored in a variable so that I can control it while in game thank you. Here's the code

When you use the spacebar to shoot, it already have the delay but I'm guessing that just is because of the keyboard delay because it's detected when it's pressed down

class Player(pygame.sprite.Sprite):
    ........
    def shoot(self):
        bullet = Bullet(self.rect.centerx, self.rect.top)
        all_sprites.add(bullet)
        bullets.add(bullet)

class Bullet(pygame.sprite.Sprite):
      def __init__(self, x, y):
          pygame.sprite.Sprite.__init__(self)
          self.image = pygame.Surface((10, 20))
          self.image.fill(RED)
          self.rect = self.image.get_rect()
          self.rect.bottom = y
          self.rect.centerx = x
          self.speedy = -10

      def update(self):
         self.rect.y += self.speedy
         # kill if it moves off the top of the screen
         if self.rect.bottom < 0:
             self.kill()

#Sprites
all_sprites = pygame.sprite.Group()
bullets = pygame.sprite.Group()
player = Player()
all_sprites.add(player)

running = True
while running:
    player.shoot()

create a variable for example shootTime and iterate it (add one) every loop, then only call the shoot function when the variable reaches twenty. once you call the shoot variable then set the variable back to zero

all_sprites = pygame.sprite.Group()
bullets = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
shootTime = 0

running = True
while running:
    shootTime += 1
    if shootTime == 20:
        player.shoot()
        shootTime = 0

you can change the number 20 in if shootTime == 20 to change the length between shots

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM