Difference between revisions of "Lighting Effects"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
Line 1: Line 1:
 +
=Intro=
 +
Many special effects can be achieved in PyGame, the easiest is a lighting effect which uses a radial gradient to control which parts of the screen can be seen. This could be used to position lights throughout your level instead of having a single light over the player.
 +
 
=Example=
 
=Example=
 
Have a look at this example:
 
Have a look at this example:

Revision as of 08:24, 19 July 2018

Intro

Many special effects can be achieved in PyGame, the easiest is a lighting effect which uses a radial gradient to control which parts of the screen can be seen. This could be used to position lights throughout your level instead of having a single light over the player.

Example

Have a look at this example:

import pygame
import sys
import os

screen=pygame.display.set_mode((640, 480))
light=pygame.image.load('circle.png') # radial gradient used for light pattern

player = pygame.image.load(os.path.join("hero.png")).convert_alpha(); # load in player image, convert_alpha will keep transparent background

player = pygame.transform.scale(player, (32, 50)) # resize player
light=pygame.transform.scale(light, (800,800)) # resize gradient

night = True # boolean to set if it is night or day

while True:
    for e in pygame.event.get():
        if e.type == pygame.QUIT: 
            pygame.quit()
            sys.exit()
            break

        if e.type == pygame.MOUSEBUTTONDOWN:
            night = not night # toggle night between true and false

    pos = []
    pos = pygame.mouse.get_pos() # get mouse position

    screen.fill(pygame.color.Color('Red')) # just a background
    for x in range(0, 640, 20):
        pygame.draw.line(screen, pygame.color.Color('Green'), (x, 0), (x, 480), 3)  # just lines on the background

    if night: # if light effect needed
        filter = pygame.surface.Surface((640, 480)) # create surface same size as window
        filter.fill(pygame.color.Color('Black')) # Black will give dark unlit areas, Grey will give you a fog
        filter.blit(light,(pos[0]-400,pos[1]-400)) # blit light to the filter surface -400 is to center effect
        screen.blit(filter, (0, 0), special_flags=pygame.BLEND_RGBA_MIN) # blit filter surface but with a blend

    screen.blit(player,pos) # blit the player over the effect
    pygame.display.flip()

It uses a radial gradient, this is my gradient:

Radial Gradient.png

It is used to light around the player. When the mouse button is pressed, night is toggled to switch between night and day.