我希望在2秒内淡入从alpha = 0到alpha = 255的矩形。使用下面的代码,我可以让矩形淡入,但我不知道让持续时间准确(尽可能精确)2秒。
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()
另外,如果我使用全屏,我应该使用标志HWSURFACE和DOUBLEBUF吗?感谢。
答案 0 :(得分:2)
我会尝试测量自操作开始以来经过的实际时间,并使alpha
与剩余时间成正比。
有些事情:
import time
def fade():
DURATION = 2.0 # seconds
start_time = time.clock()
ratio = 0.0 # alpha as a float [0.0 .. 1.0]
while ratio < 1.0:
current_time = time.clock()
ratio = (current_time - start_time) / DURATION
if ratio > 1.0: # we're a bit late
ratio = 1.0
# all your drawing details go in the following call
drawRectangle(coordinates, alpha = 255 * ratio)
fpsClock.tick(FPS)
这样,如果tick
工作不完美(它确实如此),那么你的alpha就会遵循其不完美之处,而不是累积错误。当2秒钟时,你可以保证画出一个完全不透明的矩形。