Skip to content

Instantly share code, notes, and snippets.

@petrblahos
Created December 15, 2023 11:01
Show Gist options
  • Save petrblahos/37252e7c2d9974796ca9fb138150082d to your computer and use it in GitHub Desktop.
Save petrblahos/37252e7c2d9974796ca9fb138150082d to your computer and use it in GitHub Desktop.
Starfield-like effect
import math
import random
import pygame
class Star(pygame.sprite.Sprite):
def __init__(self, center, r, angle):
super().__init__()
self.center = center
self.angle = angle
self.dist0 = self.dist = r
self.r = random.randrange(2, 6)
self.speed = random.randint(1, 5)
self.image = pygame.Surface((self.r * 2, self.r * 2), pygame.SRCALPHA)
pygame.draw.circle(self.image, (192, 255, 255), (self.r, self.r), self.r, width=0)
pygame.draw.circle(self.image, (0, 128, 128), (self.r, self.r), self.r, width=2)
def update(self, dt):
self.dist += self.speed * dt / 40
self.angle += self.speed * dt / 40000
self.speed *= 1.1
x = self.center[0] + math.sin(self.angle) * self.dist
y = self.center[1] + math.cos(self.angle) * self.dist
self.rect = self.image.get_rect(center=(x, y))
if x < 0 or x > PGMTest.WIDTH or y < 0 or y > PGMTest.HEIGHT:
self.reset()
def reset(self):
self.dist = self.dist0
self.angle = random.random() * math.pi * 2
self.speed = random.randint(1, 5)
class Glow(pygame.sprite.Sprite):
def __init__(self, center, r, angle):
super().__init__()
self.center = center
self.angle = angle
self.dist0 = self.dist = r
self.r = random.randrange(6, 12)
self.speed = random.randint(15, 25)
self.image = pygame.Surface((self.r * 2, self.r * 2), pygame.SRCALPHA)
pygame.draw.circle(self.image, (255, random.randrange(78, 220), 1), (self.r, self.r), self.r, width=0)
pygame.draw.circle(self.image, (255, 78, 1), (self.r, self.r), self.r, width=1)
def update(self, dt):
self.angle += self.speed * dt / 40000
x = self.center[0] + math.sin(self.angle) * self.dist
y = self.center[1] + math.cos(self.angle) * self.dist
self.rect = self.image.get_rect(center=(x, y))
class PGMTest:
WIDTH = 1280
HEIGHT = 600
def prepare_window(self):
self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
self.screen.fill((0, 0, 255))
def prepare_particles(self, x, y, r):
self.particles = pygame.sprite.Group()
for i in range(500):
angle = random.random() * math.pi * 2
self.particles.add(Star((x, y), r, angle))
self.particles.add(Glow((x, y), r, angle))
def run(self):
dt = 1
clock = pygame.time.Clock()
do_run = True
self.prepare_particles(self.WIDTH / 2, self.HEIGHT / 2, self.HEIGHT // 3)
while do_run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
do_run = False
break
self.screen.fill((0, 0, 0))
self.particles.update(dt=dt)
self.particles.draw(self.screen)
pygame.display.flip()
dt = clock.tick(60)
if "__main__" == __name__:
pygame.init()
pgm = PGMTest()
pgm.prepare_window()
pgm.run()
pygame.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment