[英]Im trying to make a fade in and out
我正在嘗試創建一個 function,它將為我正在制作的游戲淡入淡出。 問題是第一部分工作正常但第二部分不起作用。
WIDTH = 屏幕寬度,HEIGHT = 屏幕高度,WINDOW = window 的名稱,我將 pygame 導入為 pg
def fade():
fade = pg.Surface((WIDTH, HEIGHT))
fade.fill((0,0,0))
opacity = 0
for r in range(0, 100):
opacity += 1
fade.set_alpha(opacity)
WINDOW.blit(fade, (0,0))
pg.display.update()
pg.time.delay(10)
for r in range(0, 100):
opacity -= 1
fade.set_alpha(opacity)
WINDOW.blit(fade, (0,0))
pg.display.update()
pg.time.delay(10)
從查看代碼來看,一切都應該可以正常工作,但事實並非如此。 我沒有粘貼整個代碼,因為它有 300 行。
他們實際上做的是一遍又一遍地在背景上繪制透明圖像,直到背景完全被覆蓋。 您不能通過混合透明度較低的圖像來使背景再次可見。 您必須在每一幀中完全重繪整個場景,並在其上混合更加靈活的透明圖像。
我建議寫一個blitFadeIn
和blitFadeOut
function 並在應用程序循環中調用它。
最小的例子:
import pygame
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *background.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
[pygame.draw.rect(background, color, rect) for rect, color in tiles]
font = pygame.font.SysFont(None, 100)
text = font.render("image", True, (255, 255, 0))
image = pygame.Surface(window.get_size(), pygame.SRCALPHA)
pygame.draw.ellipse(image, "red", window.get_rect().inflate(-20, -20))
image.blit(text, text.get_rect(center = window.get_rect().center))
image.set_alpha(0)
def blitFadeIn(target, image, pos, step=2):
alpha = image.get_alpha()
alpha = min(255, alpha + step)
image.set_alpha(alpha)
target.blit(image, pos)
return alpha == 255
def blitFadeOut(target, image, pos, step=2):
alpha = image.get_alpha()
alpha = max(0, alpha - step)
image.set_alpha(alpha)
target.blit(image, pos)
return alpha == 0
fade_in = False
fade_out = False
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN:
if not fade_in and not fade_out:
fade_in = True
window.blit(background, (0, 0))
if fade_in:
done = blitFadeIn(window, image, (0, 0))
if done:
fade_in, fade_out = False, True
if fade_out:
done = blitFadeOut(window, image, (0, 0))
if done:
fade_out = False
pygame.display.flip()
pygame.quit()
exit()
另見:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.