Search code examples
pythonperformancepygamepymunk

Why is my pymunk program is way too slow?


My pymunk program is way too slow. Every time I run the program it takes 5 seconds while loading. Here is my code. Thanks in advance.

import pymunk               # Import pymunk..
import pygame
pygame.init()

display = pygame.display.set_mode((800,800))
clock = pygame.time.Clock()
space = pymunk.Space()      # Create a Space which contain the simulation
FPS = 30
def convert_coordinates(point):
    return point[0], 800-point[1]

running = True
space.gravity = 0,-1000    # Set its gravity

  # Set the position of the body
body = pymunk.Body()
shape = pymunk.Circle(body, 10)
body.position = (400,800)
shape.density = 1
space.add(body,shape)
while running:                 # Infinite loop simulation
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        pygame.display.update()
        clock.tick(FPS)
        space.step(1/FPS)
        display.fill((255,255,255))
        x,y = convert_coordinates(body.position)
        sprite = pygame.draw.circle(display,(255,0,0), (int(x),int(y)),10)
pygame.quit()

Solution

  • It's a matter of Indentation. You have to draw the scene in the application loop rather than the event loop:

    while running:                 # Infinite loop simulation
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
       
        # <--- INDENTATION     
        clock.tick(FPS)
        space.step(1/FPS)
        display.fill((255,255,255))
        x,y = convert_coordinates(body.position)
        sprite = pygame.draw.circle(display,(255,0,0), (int(x),int(y)),10)
        pygame.display.update()
            
    pygame.quit()