pythonpygamepymunk

pygame wont draw my circle in my pymunk simulation


I'm fairly new to pymunk and I wanted to make physics engine for my future games, there's just a small problem, My code won't draw the circle that pygame is trying to visualize. Here's my code.

import pygame
import pymunk
import sys


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


def draw_items(items):
    for item in items:
        pygame.draw.circle(screen, item_color, item.body.position, 80)


def quit():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()


def display_update():
    screen.fill(bg_color)
    clock.tick(FPS)
    space.step(1/60)
    pygame.display.flip()


# Constructor
pygame.init()

# Constants and Variables
WIDTH = 900
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
FPS = 60
clock = pygame.time.Clock()

# Colors
bg_color = 30, 30, 40
item_color = 200, 200, 200

# Pymunk Variables
space = pymunk.Space()
space.gravity = (0, 500)
items = []
items.append(create_item(space))


# Loops
def main():
    running = True
    while running:
        quit()
        display_update()
        draw_items(items)


main()

I don't really know what the problem is here, it doesn't give me an error or something like that and I only get a clean blank canvas with my bg color.(also sorry for the bad comments)


Solution

  • You have to draw the objects before updating the display

    def main():
        running = True
        while running:
            quit()
            screen.fill(bg_color)
            draw_items(items)
            pygame.display.flip()
            clock.tick(FPS)
            space.step(1/60)
    

    You are actually drawing on a Surface object. If you draw on the Surface associated to the PyGame display, this is not immediately visible in the display. The changes become visibel, when the display is updated with either pygame.display.update() or pygame.display.flip().

    The typical PyGame application loop has to: