在pygame中渲染消失的文本

时间:2017-07-07 05:48:47

标签: python python-3.x pygame

我正在使用pygame制作一款小游戏。当游戏开始时我想显示“开始”并在几秒钟后消失。怎么做?

2 个答案:

答案 0 :(得分:0)

首先你需要一个计时器变量(还有其他关于计时器的问题,所以我不会在这里解释)。我只是计算以下示例中的帧。

要突然删除文本,您可以保持blitting直到时间结束。

if timer > 0: 
    screen.blit(txt_surf, (position))

通过填充文本表面白色和当前的alpha值(每帧减少)并传递pg.BLEND_RGBA_MULT特殊标志,可以实现缓慢消失的文本。这只会影响曲面的alpha通道。

txt_surf.fill((255, 255, 255, alpha), special_flags=pg.BLEND_RGBA_MULT)

另外,请使用原始文本表面的副本,否则会减少先前修改过的表面的alpha值,文本也会消失得太快。

import pygame as pg


def main():
    pg.init()
    clock = pg.time.Clock()
    screen = pg.display.set_mode((640, 480))
    font = pg.font.Font(None, 64)
    orig_surf = font.render('Enter your text', True, pg.Color('royalblue'))
    txt_surf = orig_surf.copy()
    alpha = 255  # The current alpha value of the surface.
    timer = 20  # To get a 20 frame delay.

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return

        if timer > 0:
            timer -= 1
        else:
            if alpha > 0:
                # Reduce alpha each frame, but make sure it doesn't get below 0.
                alpha = max(0, alpha-4)
                # Create a copy so that the original surface doesn't get modified.                
                txt_surf = orig_surf.copy()
                txt_surf.fill((255, 255, 255, alpha), special_flags=pg.BLEND_RGBA_MULT)

        screen.fill((30, 30, 30))
        screen.blit(txt_surf, (30, 60))
        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    main()
    pg.quit()

enter image description here

答案 1 :(得分:0)

请尝试添加以下代码:

for i in range(whatevernumberbutnotover1000):
    mytext.set_alpha(i)