Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pygame Game Lighting

We are making a 2D side scrolling game and an item in the game will be a torch. We have a player who's arm can rotate and we can take the arms angle. We are looking at having a triangular beam shape, following the angle of the arm. We have had a few ideas like have an alpha image over the whole screen and individually removing alpha from each pixel based on the arm angle, but we think this will be too intensive. Any ideas would be greatly appreciated. Thanks.

like image 441
Aaron Nebbs Avatar asked Feb 10 '23 18:02

Aaron Nebbs


1 Answers

Changing pixels individually is really slow; it only works if you would use e.g. numpy to manipulate the image data, since then most work will be done in optimized, compiled C code and not in the python runtime.

An easy way is to just use another Surface to do this manipulation using a different render mode, like BLEND_RGBA_SUB.

Here's a minimal example:

import pygame
pygame.init()
screen=pygame.display.set_mode((640, 480))
light=pygame.image.load('circle.png')
while True:
    for e in pygame.event.get():
        if e.type == pygame.QUIT: break
    else:
        screen.fill(pygame.color.Color('Red'))
        for x in xrange(0, 640, 20):
            pygame.draw.line(screen, pygame.color.Color('Green'), (x, 0), (x, 480), 3)
        filter = pygame.surface.Surface((640, 480))
        filter.fill(pygame.color.Color('Grey'))
        filter.blit(light, map(lambda x: x-50, pygame.mouse.get_pos()))
        screen.blit(filter, (0, 0), special_flags=pygame.BLEND_RGBA_SUB)
        pygame.display.flip()
        continue
    break

circle.png:

enter image description here

screenshot:

enter image description here

like image 198
sloth Avatar answered Feb 12 '23 08:02

sloth