我正在尝试通过在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()
您必须计算并评估每个粒子到另一个粒子的距离。
使用2个嵌套循环。每个循环遍历粒子。如果
for particle_a in particles:
for particle_b in particles:
如果particle_a
和particle_b
相同,则continue
内部循环不做任何事情:
continue
通过if particle_a == particle_b:
continue
或Euclidean distance计算粒子之间的math.sqrt(dx*dx + dy*dy)
:
hypot(dx, dy)
如果距离小于或等于dx = particle_a.pos_x - particle_b.pos_x
dy = particle_a.pos_y - particle_b.pos_y
distance = math.sqrt(dx*dx + dy*dy)
,则停止两个粒子:
2*radius
算法
if distance <= 2*radius:
particle_a.position_locked()
particle_b.position_locked()
import math