Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind a Pyglet sprite with a Pymunk shape so they rotate together?

How do I bind a pyglet sprite to a pymunk body so that if the body is rotating the sprite also rotates?

like image 932
user1760456 Avatar asked Oct 24 '12 21:10

user1760456


1 Answers

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)

like image 140
viblo Avatar answered Sep 19 '22 04:09

viblo