user655321
user655321

Reputation: 143

Pygame Flashing Sprite After Damage

I am continuing my work using pygame and I am working on the player sprite, specifically, when it takes damage. What I would like to do is when the player takes damage from an enemy, I want the player sprite to blink 2-3 times giving the player a second or two to move from where it is taking damage. I have a health bar (3 hearts) and I set it so that every time there is a collision between an enemy and the player sprites, it will remove 1. I am using the kill() function ( I know this is wrong since it completely removes the sprite). How can I get the sprite to flash for a second or two. Any help or advice would be appreciated. thank you.

    enemy_hit_list = pygame.sprite.spritecollide(self, self.level.enemy_list, False)
    if enemy_hit_list:
        self.health -= 1
        self.kill()         

Upvotes: 1

Views: 1913

Answers (2)

Eduardo Dalapicola
Eduardo Dalapicola

Reputation: 83

def __init__(self):
    super(classname,self).__init__()
    self.image,self.rect = load_image("character.png")
    self.value = 0
    self.newColor = [0,0,0,0]

def update(self):
    self.cp = self.image.copy()
    self.value += 50
    self.newColor[0] = self.value%255 
    self.cp.fill(self.newColor[0:3] + [0,], None, pygame.BLEND_RGBA_ADD)

def render(self,screen):
    screen.blit(self.cp,self.rect)

I'm using this with clock tick 40 and work well. the update method is increasing the red value constantly for the effect. you can use another color or fill with this before the RGB_ADD command to fill with solid color.

self.cp.fill((0, 0, 0, 255), None, pygame.BLEND_RGBA_MULT)

I hope it useful for you

Upvotes: 0

jsbueno
jsbueno

Reputation: 110516

You have to specialize your class by adding an extra attribute there which will show you the flashing state. The "kill" method remvoes the sprites from any groups - I can't know from the snippet above if you are, and what is the effect. If you are using a group to actually draw the player (self), removing it from there is not the best thing to do.

You could, for example, have a "hit_countdown" attribute on your sprite, and use it's update method to change it's image accordingly, and measure the time for it to go back to normal:

class Player(Sprite):
   def __init__(self, ...):
       ...
       self.hit_countdown = 0
       ...

   def update(self, ...):
       if self.hit_coundown:
           if not hasattr(self, original_image):
              self.original_image = self.image
           if self.hit_countdown % 2:
              self.image = None # (or other suitable pre-loaded image)
           else:
              self.image = self.original_image
           self.hit_countdown = max(0, self.hit_countdown - 1)
       super(Player, self).update(...)
# and on your hit code above:
...
if enemy_hit_list:
    self.health -= 1
    self.hit_countdown = 6 

Upvotes: 1

Related Questions