Python Forum

Full Version: [pygame] transparent rects
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I made a block rectangle that is supposed to slowly go from 255 transparency to 0. I am having problems though. I don't understand this because I can slowly make it darken, but I can't get it to slowly lighten. Thanks in Advance. Here is the code -
For lightening it slowly. BTW - the indentations are weird because this is all inside a function.
#Presets
    interval = time.time()
    transparency = 255
    cover = pygame.Surface((500, 500), pygame.SRCALPHA)
    
    #Cover Screen
    while time.time() - interval < 10:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                interval -= 10

        cover.fill((0, 0, 0, transparency))
        Screen.blit(cover, (0, 0))
        if transparency != 0:
            transparency -= 1
        time.sleep(0.05)
        pygame.display.update()
        Clock.tick(fps)
That code won't work, but this code for darkening the transparency does work.
#Presets
    interval = time.time()
    transparency = 0
    cover = pygame.Surface((500, 500), pygame.SRCALPHA)
    
    #Cover Screen
    while time.time() - interval < 10:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                interval -= 10

        cover.fill((0, 0, 0, transparency))
        Screen.blit(cover, (0, 0))
        if transparency != 255:
            transparency += 1
        time.sleep(0.05)
        pygame.display.update()
        Clock.tick(fps)
Your code failed do to not clearing background first.
You need to clear background with a solid color then blits cover.
Lets also get ride of that time.sleep.
#Presets
    interval = 100 # 100 milliseconds = 0.1 seconds
    next_tick = interval + pygame.time.get_ticks()
    trans_direction = -1
    cover = pygame.Surface((500, 500), pygame.SRCALPHA)
    cover_color = pygame.Color('black')
     
    #Cover Screen
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        
        ticks = pygame.time.get_ticks()
        if ticks > next_tick:
            next_tick += interval

            cover_color.a += trans_direction
            if cover_color.a < 1:
                trans_direction = 1
            if cover_color.a > 254:
                trans_direction = -1

            cover.fill(cover_color)

        # Need to clear screen.
        Screen.fill(pygame.Color('white'))
        Screen.blit(cover, (0, 0))

        pygame.display.update()
        Clock.tick(fps)
Thanks, I don't quite understand it now, but I'll try to break it all down.