How do I bind a pyglet sprite to a pymunk body so that if the body is rotating the sprite also rotates?
Asked
Active
Viewed 1,052 times
1 Answers
4
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)

viblo
- 4,159
- 4
- 20
- 28
-
Should the `+ 180` really be there? I get a better result without it. – Flimm Jan 29 '13 at 17:32
-
1Only if your model is upside down. In the example the sprite is upside down in relation to the triangle, so it needs rotating. But normally you dont need it. I realize now that it would have been clearer without it. – viblo May 09 '17 at 20:01