user19509225
user19509225

Reputation:

how to make background colours shift in pygame?

I have a pygame game and I want to make the background color shift with screen.fill but when I do that two times in a row with different colors, the colors will change instantly but I want them to shift to the other color slowly, how is that done?

Upvotes: 1

Views: 156

Answers (1)

Rabbid76
Rabbid76

Reputation: 210878

Pygame provides the pygame.Color object. It offers the handy method lerp, that can interpolate 2 colors:

Returns a Color which is a linear interpolation between self and the given Color in RGBA space

Use this method to mix 2 colors depending on a weight w. w is 0 at the beginning and increases with time:

bg_color = color1.lerp(color2, max(0, min(1, w)))
if w < 1:
    w += 0.01

Minimal example:

import pygame

pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

color1 = pygame.Color(64, 64, 64)
color2 = pygame.Color(0, 0, 255)
w = 0

run = True
while run:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    bg_color = color1.lerp(color2, max(0, min(1, w)))
    if w < 1:
        w += 0.01

    window.fill(bg_color)
    pygame.display.flip()

pygame.quit()
exit()

Upvotes: 2

Related Questions