Search code examples
pythonpygamephysicspymunk

Pymunk Body moving without moving pymunk shape vertices


My goal with this code is to demonstrate a rectangle falling in pymunk using pygame.

import pymunk
import pygame

pygame.init()
screen = pygame.display.set_mode((1280, 720))

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

mass = 1

chassis_shape = pymunk.Poly.create_box(None, size=(100, 100))
chassis_moment = pymunk.moment_for_poly(mass, chassis_shape.get_vertices())
chassis = pymunk.Body(mass, chassis_moment)
chassis_shape.body = chassis
chassis.position = 250, 100


space.add(chassis_shape, chassis)


def draw_poly(shape):
    pygame.draw.polygon(screen, [255, 255, 255], shape.get_vertices())


while True:
    screen.fill([0, 0, 0])
    draw_poly(chassis_shape)
    print(chassis_shape.get_vertices(), chassis.position)
    space.step(0.02)
    pygame.display.update()

When I run this program, the body object moves fine, however the vertices from the shape remain stationary. How would I modify this so that the display window has the object move at all? Other questions have left out things like the pymunk step, or have otherwise been irrelevant.


Solution

  • The problem is that get_vertices() returns the local coordinates. You need to manually account for rotation and global displacement, like in the following

    def draw_poly(shape):
        verts = []
        for v in shape.get_vertices():
            x = v.rotated(shape.body.angle)[0] + shape.body.position[0]
            y = v.rotated(shape.body.angle)[1] + shape.body.position[1]
            verts.append((x, y))
        pygame.draw.polygon(screen, [255, 255, 255], verts)