How do I bind a pyglet sprite to a pymunk body so that if the body is rotating the sprite also rotates?
There is no built in syncing so you have to do it on your own each frame. But dont worry, its very easy.
If you have your body positioned in the middle of the shape/shapes, and the image is the same size there's two things you need. First, set the image anchor to half its size. Then in your update method you loop the bodies you want to sync and set the sprite position to the body position and sprite rotation to body rotation converted into degrees. You might also need to rotate it 180 degrees (in case your model is flipped) and/or invert the rotation.
In code
img = pyglet.image.load('img.png')
img.anchor_x = img.width/2
img.anchor_y = img.height/2
sprite = pyglet.sprite.Sprite(img)
sprite.body = body
def update(dt):
sprite.rotation = math.degrees(-sprite.body.angle)
sprite.set_position(sprite.body.position.x, sprite.body.position.y)
For a full example take a look at this example I created: https://github.com/viblo/pymunk/blob/master/examples/using_sprites_pyglet.py
(Im the author of pymunk)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With