I'm attempting to make a simulation by generating particles (mainly circles) in pygame. One objective is to have the particle move randomly on the screen and once they collide, they should stick to each other and stay in their fixed position. I created a class called Particle which takes the following attributes: Particles(pos_x, pos_y, size, colour, screen)
. Then I generate a list of these particles on the screen so that they move randomly. However, I'm having a hard time conceptualizing how to loop through every particle and check if the distance between their respective x coordinates is less than 2*radius
. (Example: if the radius of a particle is 5pixels, then particle_a(4, 8)
would collide with particle_b(6, 8)
.
How would I go about checking each particle to see if they collide with each other? looping through a list of particles and then checking with a copy of that list but I'm not sure I'm going about this the right way. I can use all the help I can get. I'm still a beginner so I'd appreciate any help.
import sys
import pygame
import random
from dla_settings import Settings
from particles import Particles
PARTICLE_SIZE = 5
PARTICLE_COLOUR = (random.choice((200, 240)), 100, 0)
def dla_simulation():
dla_settings = Settings()
pygame.init()
screen = pygame.display.set_mode((dla_settings.screen_width, dla_settings.screen_height))
pygame.display.set_caption("DLA")
screen.fill((10, 10, 10))
pygame.display.update()
main_particle = Particles(dla_settings.screen_width // 2,
dla_settings.screen_height // 2,
PARTICLE_SIZE,
PARTICLE_COLOUR,
screen)
particles = []
for particle in range(20):
x = random.randint(400, 500)
y = random.randint(400, 500)
particle = Particles(x,
y,
PARTICLE_SIZE,
PARTICLE_COLOUR,
screen)
particles.append(particle)
particles_copy = particles.copy()
print(particles_copy)
# Start the main loop for the game.
while True:
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill((10, 10, 10))
main_particle.draw_particle()
for particle in particles:
particle.draw_particle()
particle.random_move()
for particle_copy in particles_copy:
if particle.pos_x - particle_copy < 2:
particle.position_locked()
# Update screen
pygame.display.flip()
dla_simulation()