2 回答
TA贡献2003条经验 获得超2个赞
a 的当前位置Body
存储在position
属性中(例如space.bodies[0].position
)。
PyGame 使用左上角为 (0, 0) 的坐标系。y 轴需要反转 ( screen.get_height() - pos[1]
),因为 y 轴一般指向上,但在 PyGame 坐标系中 y 轴指向下。
running = True
while 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 = True
while 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 pymunk
import pymunk.pygame_util
import pygame
import math
GRAY = (220, 220, 220)
width_mass=50
height_mass=50
pygame.init()
size = 800,600
screen = 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.5
body = pymunk.Body(mass=1, moment=100)
body.position = 400,400
mass = pymunk.Poly.create_box(body, (width_mass, height_mass))
mass.elasticity = 0
space.add(body, mass)
running = True
while 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)
TA贡献1898条经验 获得超8个赞
使 Pymunk 模拟的行为类似于本机 PyGame 坐标。您只需将以下行添加到您的代码中即可。
pygame.pygame_util.positive_y_is_up = True
自 PyMunk 6.0 起已默认为 True。
添加回答
举报