Home > Mobile >  Why is the explosion showing immediately?
Why is the explosion showing immediately?

Time:02-02

I am trying to handle the collision with shot and asteroid, but after the collision I want to add an explosion.

I added a timer so the explosion is going to show on the screen after some time, but the the explosion shows immediately, and I dont see the problem. This is the function with the problem in my code.

def handle_collision_with_shot_asteroid(self):
    for asteroid_rect in self.asteroid_list:
        for shot_rect in self.shots:
            # check for collision
            if asteroid_rect.colliderect(shot_rect):
                # remove the shot and the asteroid from the screen
                self.asteroid_list.remove(asteroid_rect)
                self.shots.remove(shot_rect)

                # create an effect after the asteroid get shot
                explosion_rect = self.explosion_big.get_rect(center=(asteroid_rect.x 29, asteroid_rect.y 29))


                # record the time the explosion started
                self.explosion_start_time = pygame.time.get_ticks()
    try:            
        if pygame.time.get_ticks() - self.explosion_start_time > 1000:
            # show the explosion
            screen.blit(self.explosion_big, explosion_rect)

            # Reset the explosion start time so it doesn't show again
            self.explosion_start_time = 0
    except:
        pass

CodePudding user response:

I believe that you should be doing something like

  if pygame.time.get_ticks() - self.explosion_start_time > 2000:

Also check if the api for ticks() returns what you expect it to.

CodePudding user response:

i fix it with this code:

def handle_collision_with_shot_asteroid(self):

    for asteroid_rect in self.asteroid_list:

        for shot_rect in self.shots:
            # check for collision
            if asteroid_rect.colliderect(shot_rect):
                # remove the shot and the asteroid from the screen
                self.asteroid_list.remove(asteroid_rect)
                self.shots.remove(shot_rect)

                # record the time the explosion started
                self.explosion_start_time = pygame.time.get_ticks()

                # defined the x,y of the explosion
                self.x,self.y = asteroid_rect.x-20, asteroid_rect.y 15

    
    if self.explosion_start_time:
        if pygame.time.get_ticks() - self.explosion_start_time > 200:
            # show the explosion
            screen.blit(self.explosion_big, (self.x,self.y))
            

            # Reset the explosion start time so it doesn't show again
            self.explosion_start_time = 0
        
        
  • Related