In one of my previous tutorials, I have demonstrated how to create a simple starfield simulation using Python and Pygame. Today, we will make a few modifications in the code from that tutorial to make a pretty cool parallax starfield. The video below shows the parallax starfield in action.
The idea of the parallax effect is to make distant objects appear to be moving slower than closer objects. As you can see in the video, distant stars are smaller and move at a slower speed, in contrast to closer stars that are faster and bigger. To make this even more interesting, I made closer stars brighter than distant stars.
If you compare this code with the code from the simple starfield tutorial, you will see I have made very few modifications. I have basically added a speed attribute to the stars, so they are now represented as a list with the format [X,Y,Speed]. The speed attribute can be 1,2 or 3, and it indicates the speed of the stars, but is also used to determine their color and size.
import pygame from random import randrange, choice MAX_STARS = 250 STAR_SPEED = 2 def init_stars(screen): """ Create the starfield """ global stars stars =  for i in range(MAX_STARS): # A star is represented as a list with this format: [X,Y,speed] star = [randrange(0,screen.get_width() - 1), randrange(0,screen.get_height() - 1), choice([1,2,3])] stars.append(star) def move_and_draw_stars(screen): """ Move and draw the stars in the given screen """ global stars for star in stars: star += star # If the star hit the bottom border then we reposition # it in the top of the screen with a random X coordinate. if star >= screen.get_height(): star = 0 star = randrange(0,639) star = choice([1,2,3]) # Adjust the star color acording to the speed. # The slower the star, the darker should be its color. if star == 1: color = (100,100,100) elif star == 2: color = (190,190,190) elif star == 3: color = (255,255,255) # Draw the star as a rectangle. # The star size is proportional to its speed. screen.fill(color,(star,star,star,star)) def main(): # Pygame stuff pygame.init() screen = pygame.display.set_mode((640,480)) pygame.display.set_caption("Parallax Starfield Simulation") clock = pygame.time.Clock() init_stars(screen) while True: # Lock the framerate at 50 FPS clock.tick(50) # Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: return screen.fill((0,0,0)) move_and_draw_stars(screen) pygame.display.flip() if __name__ == "__main__": main()
Click here to download the source code.
In this tutorial we made a vertical parallax starfield. Try to modify the code to make an horizontal starfield.
That’s everything for now. In the next tutorial I will show you how to make a 3D starfield simulation.
What do you think about this? Please comment, share or subscribe.