0

I wrote a python game using pygame and pymunk, but the playground() section doesnt work. It supposed to show a static object, but it doesnt. I asked and it was supposed to interact with balls being dropped. heres the code:

import pygame, sys
import pymunk
import pymunk.pygame_util
from pymunk.vec2d import Vec2d
size = (800, 600)
FPS = 120

space = pymunk.Space()
space.gravity = (0,250)

pygame.init()
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()

class Ball:
    global space
    def __init__(self, pos):
        self.body = pymunk.Body(1,1, body_type = pymunk.Body.DYNAMIC)
        self.body.position = pos
        self.radius = 60
        self.shape = pymunk.Circle(self.body, self.radius)

        space.add(self.body, self.shape)

    # INDENTATION
    #<--|

    def draw(self):
        x = int(self.body.position.x)
        y = int(self.body.position.y)
        pygame.draw.circle(screen, (255,0,0), (x,y), self.radius)

def playground():
    body = pymunk.Body(1,1, body_type = pymunk.Body.STATIC)

balls = []
balls.append(Ball((400,0)))
balls.append(Ball((100,0)))
balls.append(Ball((600,100)))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            balls.append(Ball(event.pos))
    # INDENTATION
    #<------|    

    screen.fill((217,217,217))

    for ball in balls:
        ball.draw()

    playground()

    space.step(1/50)
    pygame.display.update()
    clock.tick(FPS)

Any solution? Its for a school project so any help will greated. Thanks.

  • 2
    Pygame is used to draw to your screen. Pymunk simulates physics. You will have to draw with pygame at the position of your object generated by pymunk. Also you shouldn't create a new body each frame. – Jerry Aug 01 '22 at 15:30

1 Answers1

1

You forgot to add the body into the space, that's why the balls kept on falling. You also need to define the shape of the body which is a required argument in adding to space. Lastly, you need to draw into pygame screen the shape as previously defined.

def playground():
    body = pymunk.Body(1,1, body_type = pymunk.Body.STATIC)
    polygon_points = [(0,580),(800,580),(800,600),(0,600)]
    shape = pymunk.Poly(space.static_body, polygon_points)
    space.add(body, shape)
    pygame.draw.polygon(screen, (0, 0, 0), polygon_points)
Jobo Fernandez
  • 905
  • 4
  • 13