Python Pygame Game Lighting

8k views Asked by At

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

1

There are 1 answers

0
sloth On BEST ANSWER

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