湖上湖
a 的当前位置Body存储在position属性中(例如space.bodies[0].position)。PyGame 使用左上角为 (0, 0) 的坐标系。y 轴需要反转 ( screen.get_height() - pos[1]),因为 y 轴一般指向上,但在 PyGame 坐标系中 y 轴指向下。running = Truewhile running: # [...] # draw a dot in at the center of the bodies for body in space.bodies: pos = body.position pygame.draw.circle(screen, (255,0,0), (pos[0], screen.get_height()-pos[1]), 7) pygame.display.update() space.step(0.01)a 的当前角度Body存储在angle属性中(例如body_type.angle)。可以通过将旋转的相对位置与绝对位置相加来计算点的当前位置。旋转位置可以通过简单的三角函数计算:pos = abs_pos[0] + rel_dist * math.cos(angle), abs_pos[1] + rel_dist * math.sin(angle)首先,您必须根据相对笛卡尔坐标计算相对极坐标:rel_pos = (0, 238.5)
rel_dist, rel_angle = math.hypot(*rel_pos), math.atan2(rel_pos[1], rel_pos[0])将当前角度添加到极坐标角度:angle = rel_angle + body_type.angle例如:running = Truewhile running: # [...] abs_pos = body_type.position rel_pos = (0, 238.5) rel_dist, rel_angle = math.hypot(*rel_pos), math.atan2(rel_pos[1], rel_pos[0]) angle = rel_angle + body_type.angle pos = abs_pos[0] + rel_dist * math.cos(angle), abs_pos[1] + rel_dist * math.sin(angle) pygame.draw.circle(screen, (255, 255, 0), (pos[0], screen.get_height() - pos[1]), 7) pygame.display.update() space.step(0.01)最小的例子:import pymunkimport pymunk.pygame_utilimport pygameimport mathGRAY = (220, 220, 220)width_mass=50height_mass=50pygame.init()size = 800,600screen = pygame.display.set_mode(size)draw_options = pymunk.pygame_util.DrawOptions(screen)space = pymunk.Space()space.gravity = (0,-50)pts = [(-27, -238.5), (27,-238.5), (27,238.5), (-27,238.5)]body_type=pymunk.Body(body_type=pymunk.Body.KINEMATIC) body_type.position = (400, 263.5) space.add(body_type)for i in range(4): segment = pymunk.Segment(body_type, pts[i], pts[(i+1)%4], 2) segment.elasticity = 0 segment.friction=0 space.add(segment)body_type.angular_velocity=0.5body = pymunk.Body(mass=1, moment=100)body.position = 400,400mass = pymunk.Poly.create_box(body, (width_mass, height_mass))mass.elasticity = 0space.add(body, mass)running = Truewhile running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False #pygame.image.save(screen, 'intro1.png') screen.fill(GRAY) space.debug_draw(draw_options) for body in space.bodies: pos = body.position pygame.draw.circle(screen, (255, 0, 0), (pos[0], screen.get_height() - pos[1]), 7) abs_pos = body_type.position rel_pos = (0, 238.5) rel_dist, rel_angle = math.hypot(*rel_pos), math.atan2(rel_pos[1], rel_pos[0]) angle = rel_angle + body_type.angle print( body_type.position.angle) pos = abs_pos[0] + rel_dist * math.cos(angle), abs_pos[1] + rel_dist * math.sin(angle) pygame.draw.circle(screen, (255, 255, 0), (pos[0], screen.get_height() - pos[1]), 7) pygame.display.update() space.step(0.01)