Skip to content Skip to sidebar Skip to footer

How To Make An Object Fades Color In Pygame

I want a rectangle to fade from green to red for a life-bar, but couldn't find easy way to do it on internet. I tried like this (just for going from red to yellow): colorR = 0 colo

Solution 1:

To make changes to the display surface visible you have to call pygame.display.flip() or pygame.display.update(). Furthermore I recommend to handle the events by either pygame.event.get() or pygame.event.pump(). Note you have to do a delay in the loop, otherwise the color will fade rapidly. If the color is not in range [0, 255] you'll get "invalid color argument" error. That happens because the loop in your example never terminates. You missed change = False.

anyway, since you have a application loop, there is no need to do the fade in a separate loop. Use the main application loop:

game = True
colorR = 0
colorG = 255
colorB = 0defrgw(): 
    global colorR, colorG, colorB
    win.fill((0, 0, 255))
    if game:
        pygame.draw.rect(win, (colorR, colorG, colorB), (10, 10, 200, 50), 0)
        if colorR < 255:
            colorR += 1
    pygame.display.update()

run = Truewhile run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = Falseif event.type == pygame.MOUSEBUTTONDOWN:
            game = Trueelif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE:
                run = False

    rgw()

pygame.quit()

Post a Comment for "How To Make An Object Fades Color In Pygame"