我有一个动态对象,我为其设置了不同的速度值。然而,当这个动态物体撞到一个静态物体时,它会与静态形状部分重叠,直到这个碰撞被解决并向后移动。
pymunk 中是否有办法让动态体精确地停在静态体的边界上,即使在这个方向上应用速度也是如此?如果存在碰撞冲突,我宁愿以另一种方式解决它们,而不是使两个形状重叠。
施加力和脉冲并不是一个真正的选择,因为我想要一个恒定的速度。
(下面的代码需要执行两次才能工作。)
import pymunk
import pyglet
from PIL import Image
from PIL import ImageDraw
# setup of pyglet
window = pyglet.window.Window()
main_batch = pyglet.graphics.Batch()
keys = pyglet.window.key.KeyStateHandler()
window.push_handlers(keys)
# setup of pymunk
space = pymunk.Space()
"""MOVABLE CIRCLE"""
# creating pyglet sprite
circle_img = Image.new('RGBA', (50,50))
draw = ImageDraw.Draw(circle_img)
draw.ellipse((1, 1, 50-1, 50-1), fill=(255,0,0))
circle_img.save('circle.png')
pyglet_circle_img = pyglet.resource.image('circle.png')
pyglet_circle_img.anchor_x = pyglet_circle_img.width/2
pyglet_circle_img.anchor_y = pyglet_circle_img.height/2
circle_sprite = pyglet.sprite.Sprite(pyglet_circle_img, window.width/2, window.height/2, batch=main_batch)
# creating pymunk body and shape
mass = 2
radius = 25
moment = pymunk.moment_for_circle(mass, 0, radius)
circle_body = pymunk.Body(mass, moment)
circle_body.position = circle_sprite.position
circle_shape = pymunk.Circle(circle_body, 25)
circle_shape.elasticity = 0.0
space.add(circle_body, circle_shape)
"""STATIC SQUARE"""
# creating pyglet sprite
square_img = Image.new('RGBA', (70,70))
draw = ImageDraw.Draw(square_img)
draw.rectangle([(0, 0), (70-1, 70-1)], fill=(0,255,0))
square_img.save('square.png')
pyglet_square_img = pyglet.resource.image('square.png')
pyglet_square_img.anchor_x = pyglet_square_img.width/2
pyglet_square_img.anchor_y = pyglet_square_img.height/2
square_sprite = pyglet.sprite.Sprite(pyglet_square_img, 3*window.width/4, window.height/2, batch=main_batch)
# creating pymunk body and shape
square_body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
square_body.position = square_sprite.position
square_shape = pymunk.Poly(square_body, [(-35,-35),(-35,35),(35,35),(35,-35)])
square_shape.elasticity = 0.0
space.add(square_body, square_shape)
def update(dt):
space.step(dt)
circle_sprite.position = circle_body.position
print(circle_body.position)
key_pressed = False
if keys[pyglet.window.key.LEFT]:
circle_body.velocity = (-100,0)
key_pressed = True
elif keys[pyglet.window.key.RIGHT]:
circle_body.velocity = (100, 0)
key_pressed = True
if keys[pyglet.window.key.UP]:
circle_body.velocity = (0, 100)
key_pressed = True
elif keys[pyglet.window.key.DOWN]:
circle_body.velocity = (0, -100)
key_pressed = True
if not key_pressed:
circle_body.velocity = (0,0)
@window.event
def on_draw():
window.clear()
main_batch.draw()
pyglet.clock.schedule_interval(update, 1/60.)
pyglet.app.run()