Skip to content Skip to sidebar Skip to footer

Pygame Set_alpha Not Working With Attempted Background Fading

I've been trying to create a short code to use for a project that can fade in and from black, but for some reason only the function that fades in is working while the fade out func

Solution 1:

When you draw a transparent surface on the screen, the surface is blended with the current contents of the screen. Hence you need to clear the screen before drawing the fading background with screen.fill(0).


Do not try to control the application recursively or with loops within the application loop. Do not delay the game. delay causes the game to stop responding.

Use the application loop and use pygame.time.Clock to control the frames per second and thus the game speed.

The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():

This method should be called once per frame.

That means that the loop:

clock = pygame.time.Clock()
run = Truewhile run:
   clock.tick(60)

Example:

import pygame

pygame.init()
screen = pygame.display.set_mode((400,300))
clock = pygame.time.Clock()

try:
    image = pygame.image.load_extended('Map.png').convert_alpha()
    image = pygame.transform.scale(image,(530,300))
except:
    image = pygame.Surface(screen.get_size())
    pygame.draw.circle(image, (255, 0, 0), screen.get_rect().center, min(*screen.get_size()) // 2 - 20)

alpha = 0
alpha_change = 1

run = Truewhile run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False          

    alpha += alpha_change
    ifnot0 <= alpha <= 255:
        alpha_change *= -1
    alpha = max(0, min(alpha, 255))   

    screen.fill(0)

    alpha_image = image.copy()
    alpha_image.set_alpha(alpha)    
    screen.blit(alpha_image, (0, 0))
    
    pygame.display.flip()

pygame.quit()
exit()

Post a Comment for "Pygame Set_alpha Not Working With Attempted Background Fading"