我正在尝试通过在pygame中生成粒子(主要是圆形)来进行模拟。其中一个目标是让粒子在屏幕上随机移动,一旦它们碰撞,就应该粘在一起并保持在固定位置。我创建了一个名为Particle的类,它具有以下属性:
我该如何检查每个粒子是否与其他粒子相碰撞?我考虑循环遍历粒子列表,然后再用该列表的副本进行检查,但我不确定这样做是否正确。我需要帮助。由于我是初学者,所以我会感激任何帮助。
Particles(pos_x, pos_y, size, colour, screen)
。然后我在屏幕上生成这些粒子的列表,以便它们可以随机移动。然而,我难以想象如何循环遍历每个粒子并检查它们各自的x坐标之间的距离是否小于2*radius
(例如:如果一个粒子的半径是5像素,则particle_a(4, 8)
将与particle_b(6, 8)
发生碰撞)。我该如何检查每个粒子是否与其他粒子相碰撞?我考虑循环遍历粒子列表,然后再用该列表的副本进行检查,但我不确定这样做是否正确。我需要帮助。由于我是初学者,所以我会感激任何帮助。
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()