I want to fade in a rectangle from alpha = 0 to alpha = 255 over 2 seconds. Using the following code, I am able to get the rectangle fade in but I don’t know to get the duration to be exactly (as exact as possible) 2 seconds.
pygame.init()
#frames per second setting
FPS = 30
fpsClock = pygame.time.Clock()
#Set up window
screen = pygame.display.set_mode((1280,800))
shape = screen.convert_alpha()
#Colors
alpha = 0
WHITE = (255, 255, 255,alpha)
BLACK = (0,0,0)
#Stimuli
stimulus = pygame.Rect(100,250,100,100)
def fade():
"""Fades in stimulus"""
global alpha
alpha = alpha + 5 <--- (Do I change this increment?)
#Draw on surface object
screen.fill(BLACK)
shape.fill(BLACK)
pygame.draw.rect(shape,(255, 255, 255,alpha),stimulus)
screen.blit(shape,(0,0))
pygame.display.update(stimulus)
fpsClock.tick(FPS)
while True:
fade()
Additionally, should I use the flags HWSURFACE and DOUBLEBUF if I am using fullscreen? Thanks.
I would try to measure actual time passed since the operation start and make
alphadirectly proportional to the remaining time.Something along the lines:
This way, if
tickworks imperfectly (which it does), your alpha follows its imperfections, instead of accumulating the error. When 2 seconds are up, you’re guaranteed to have drawn a fully opaque rectangle.