如何在 pybox2d 中实现 MouseJoint?
python 532
原文标题 :How to implement a MouseJoint in pybox2d?
我正在尝试在 pybox2d 中使用鼠标移动动态主体。以下是我尝试过的最小的、可重现的代码。
import pyglet
import Box2D
from Box2D import *
window = pyglet.window.Window(resizable=True)
object = pyglet.shapes.Rectangle(x=0,y=0,width=20,height=20,color=(255,255,0))
ground = pyglet.shapes.Rectangle(x=0,y=0,width=20,height=20,color=(255,0,0))
world = Box2D.b2World()
ground_body = world.CreateStaticBody()
object_body = world.CreateDynamicBody(position=(1, 0.25),shapes=b2PolygonShape(box=(0.1,0.1)))
support_body = world.CreateStaticBody(position=(0, 0),shapes=b2PolygonShape(box=(5,0.1)))
mouse_joint = None
object_body.awake = True
@window.event
def on_draw():
window.clear()
object.draw()
@window.event
def on_mouse_press(x, y, button, modifiers):
global mouse_joint
mouse_joint = world.CreateMouseJoint(bodyA=ground_body,bodyB=object_body, target=object_body.position)
object_body.awake = True
@window.event
def on_mouse_release(x, y, button, modifiers):
global mouse_joint
if mouse_joint:
world.DestroyJoint(mouse_joint)
mouse_joint = None
@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
if mouse_joint:
mouse_joint.target = (x/100,y/100) # Taking one meter as 100 pixels
def update(dt):
world.Step(dt, 5, 5)
if mouse_joint:
print(mouse_joint.target, object_body.position.x, object_body.position.y)
object.x = (object_body.position.x-0.1) * 100
object.y = (object_body.position.y-0.1) * 100
pyglet.clock.schedule_interval(update, 1/60.)
pyglet.app.run()
但是对象没有跟随鼠标。它停留在支撑体上,好像不受鼠标关节的影响。我该如何解决这个错误?提前致谢!