Pymunk身体移动而没有移动Pymunk形状顶点

时间:2018-08-08 13:29:09

标签: python pygame physics pymunk

此代码的目标是演示使用pygame落入pymunk中的矩形。

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()

当我运行该程序时,身体对象运动良好,但是形状的顶点保持静止。我将如何修改此显示窗口以使对象完全移动?其他问题遗漏了诸如pymunk步骤之类的东西,或者与之无关。

1 个答案:

答案 0 :(得分:1)

问题是get_vertices()返回本地坐标。您需要手动考虑旋转和整体位移,如下所示:

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)