首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >意外粒子模拟行为

意外粒子模拟行为
EN

Stack Overflow用户
提问于 2022-09-06 06:16:30
回答 1查看 38关注 0票数 0

在基本粒子模拟器上工作,其中规则可以应用于粒子组(例如。红色吸引蓝色,蓝色排斥黄色等)。使用这段视频作为指导,我创建了一个简单的python应用程序,它可以工作,但是粒子的行为并不像预期的那样。下面的代码是一个例子,蓝色粒子开始被红色粒子吸引,但不是振荡,而是从红色粒子上反弹而变得混沌。

代码语言:javascript
复制
import pygame
import random

class Particle():
    def __init__(self, x, y, mass, color):
        self.x = x
        self.y = y
        self.xvel = 0
        self.yvel = 0
        self.mass = mass
        self.color = color

def main():
    random.seed(1662443792)

    # initialize screen
    pygame.init()
    width = 1000
    height = 800
    screen = pygame.display.set_mode((width, height))
    clock = pygame.time.Clock()
    running = True

    # spawn some particles
    blue = []
    for i in range(1):
        x = random.randint(0, width)
        y = random.randint(0, height)
        p = Particle(x, y, 1, (0, 0, 255))
        blue.append(p)
    red = []
    for i in range(1):
        x = random.randint(0, width)
        y = random.randint(0, height)
        p = Particle(x, y, 10, (255, 0, 0))
        red.append(p)

    while running:
        pygame.display.flip()
        screen.fill((0, 0, 0))
        draw_particles(screen, blue)
        draw_particles(screen, red)
        rule(blue, red, -1)
        clock.tick(144)

        # quit simulation
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                pygame.quit()

# PHYSICS FOR PARTICLES DONE HERE               
def rule(set1, set2, g):
    for a in set1:
        fx = 0
        fy = 0
        for b in set2:
            # calculate distance between particles
            dx = a.x - b.x
            dy = a.y - b.y
            d = (dx * dx + dy * dy) ** .5
            if (d > 0):
                # calculate force between particles
                force = (g * a.mass * b.mass) / (d*d)
                fx += force * dx
                fy += force * dy
        # update force and position
        a.xvel = (a.xvel + fx)
        a.yvel =  (a.yvel + fy)
        a.x += a.xvel
        a.y += a.yvel
        # if particle wants to leave screen, flip velocity
        if (a.x >= 1000 or a.x <= 0):
            a.xvel *= -1
        if (a.y >= 800 or a.y <= 0):
            a.yvel *= -1

def draw_particles(screen, particle_set1):
    for p in particle_set1:
        pygame.draw.circle(screen, p.color, (p.x, p.y), 5, 2)

if __name__ == '__main__':
    main()
EN

回答 1

Stack Overflow用户

发布于 2022-09-06 06:56:05

我相信你对力的估计是不恰当的。你把它乘以dx,我想得到力的“方向”,但是你应该除以d

另外,关于你的速度和位置更新,我认为你高估了两者的变化,而不是a.xvel += fx,我会期望a.xvel += fx*dt,用dt你的集成步骤,这里我猜是0.144s。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73617475

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档