使用Pygame和Pymunk Circle不会在太空中生成

问题描述

因此,我尝试制作一个函数create_particle,然后使该函数使用draw_circle进行部分绘制。但是,每当我打开窗口时,都会看到灰色的窗口,但没有显示任何粒子。我对pygame和pymunk都非常陌生,因此可以提供任何帮助。

import sys,pygame,random,pymunk

BG = (94,93,93)
S_width = 800
S_height = 800

pygame.init()
Window = pygame.display.set_mode((S_width,S_height))
clock = pygame.time.Clock()
pygame.display.set_caption("H20 Particle simulation")
Window.fill(BG)
space = pymunk.Space()
space.gravity = (0,100)

def create_particle(space):
    body = pymunk.Body(1,100,body_type = pymunk.Body.DYNAMIC)
    body.position = (400,400)
    shape = pymunk.Circle(body,80)
    space.add(body,shape)
    return shape

def draw_circle(circle):
    for circle in circles:
        pos_x = int(circle.body.position.x)
        pos_y = int(circle.body.position.y)
        pygame.draw.circle(screen,(0,0),circle.body.position20)

circles = []
circles.append(create_particle(space))



while True:
    Window.fill((217,217,217))
    clock.tick(120)
    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

解决方法

需要一些更改:

  • draw_circle()不需要参数
  • 绘制圆时,需要指定坐标和半径
  • 在主循环中,调用draw_circle()space.step(0.02)

这是更新的代码:

def draw_circle():
    for circle in circles:
        pos_x = int(circle.body.position.x)
        pos_y = int(circle.body.position.y)
        pygame.draw.circle(Window,(0,200,0),(pos_x,pos_y),20)

circles = []
circles.append(create_particle(space))

while True:
    Window.fill((217,217,217))
    draw_circle()
    space.step(0.02)
    clock.tick(120)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit() 
    pygame.display.update()