0

i have a code that pops up a speechbubble when the player hits a rectangle. But now its just spamming the speech bubble. Thats not good because i have random texts that appears so it's just going through it very fast

this is the code for the speech bubble

def draw_speech_bubble(screen, text, text_color, bg_color, pos, size):

    font = pygame.font.SysFont(None, size)
    text_surface = font.render(text, True, text_color)
    text_rect = text_surface.get_rect(midbottom=pos)

    #Background Object
    bg_rect = text_rect.copy()
    bg_rect.inflate_ip(10,10)

    #Border
    border_rect = bg_rect.copy()
    border_rect.inflate_ip(4,4)
    
    pygame.draw.rect(screen, text_color, border_rect)
    pygame.draw.rect(screen, bg_color, bg_rect)
    screen.blit(text_surface, text_rect)

This is my code for the collision

if(player.player_rect.colliderect(BarCounter)):
    draw_speech_bubble(screen, str(RandomText()), (255, 255, 255), (0, 0,0),SpeechBubbleAnchor.midtop,25)

I want some sort of cooldown so it doesn't spam the speechbubbles. I tried making a calculation with ticks but i wasn't able to do that

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

1

Add a variable that stores the text (current_bubble_text) and change the text when the player hits the rectangle. Use pygame.time.get_ticks() to get the number of milliseconds since pygame.init() was called. Calculate the point in time at which the text has to disappear again. When the time comes, reset the variable:

current_bubble_text = None
bubble_text_end_time = 0

#application loop
while True:
    current_time = pygame.time.get_ticks()
    # [...]

    if current_bubble_text == None and player.player_rect.colliderect(BarCounter):
        current_bubble_text = RandomText()
        bubble_text_end_time = current_time + 5000 # 1 second time interval

    if current_bubble_text:
         draw_speech_bubble(screen, current_bubble_text,
             (255, 255, 255), (0, 0, 0), SpeechBubbleAnchor.midtop, 25)
         if current_time > bubble_text_end_time:
             current_bubble_text = None 
    # [...]

See also Adding a particle effect to my clicker game.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174