我试图通过在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个嵌套循环。每个循环都会迭代粒子。如果
如果} 不做任何操作就执行内部循环:
particle_a
和particle_b
是相同的,那么^{通过
math.sqrt(dx*dx + dy*dy)
或hypot(dx, dy)
计算粒子之间的Euclidean distance:如果距离小于或等于
2*radius
,则停止两个粒子:算法
相关问题 更多 >
编程相关推荐