Search code examples
pythonpygamepymunk

Python PyMunk acts weirdly


here is the problem :

My pymunk code is from https://pymunk-tutorial.readthedocs.io/en/latest/shape/shape.html

But when i launch the program, a weird force acts on the segment. See the result : https://youtu.be/s4a0RLb6Y6k

See the code : (without useless part about dependencies)

import pymunk
import pymunk.pygame_util

import pygame
from pygame.locals import *





pygame.init()

width, height = 1280, 720

window = pygame.display.set_mode((width, height), FULLSCREEN)

draw_options = pymunk.pygame_util.DrawOptions(window)
window.fill((0,0,0))







run = True

space = pymunk.Space()
space.gravity = 0, -1000


b0 = space.static_body
sol = pymunk.Segment(b0, (0, 30), (width, 30), 10)
sol.elasticity = 1

body = pymunk.Body(mass=1, moment=1000)
body.position = (width/2, 50)
segment = pymunk.Segment(body, (width/2-20,50), (width/2+20,50), 1)
segment.elasticity = 0.95

space.add(sol, body, segment)


while run == True:
    space.step(0.01)


    window.fill((0,0,0))
    pygame.draw.line(window, (0, 255, 0), (0, height-30), (width, height-30), 1)
    space.debug_draw(draw_options)
    pygame.display.flip()
    pygame.time.Clock().tick(60)


    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                run = False
        if event.type == QUIT:
            run = False
        mouse_x, mouse_y = pygame.mouse.get_pos()
        pass

    continue 

I don't see where is the problem.. Thanks by advance


Solution

  • One common reason why strange behavior like that in the video happens is because center of gravity of the shape is not in the actual center. Try changing so that you make the Segment around the its center (0,0), where the body is.

    Something like this maybe

    segment = pymunk.Segment(body, (-20,0), (20,0), 1)
    

    If you want to move it you can adjust the position of the body instead.