How to associate a pirate sprite with a Pymunk shape so that they rotate together?

How to connect a pigment sprite with a blacksmith body, so that if the body rotates, the sprite also rotates?

+7
source share
1 answer

There is no built-in synchronization, so you have to do it yourself for each frame. But do not worry, it is very easy.

If you have your body located in the middle of the figure / figures, and the image is the same size, you need two things. First, set the image anchor to half its size. Then, in your update method, you loop the bodies that you want to synchronize, and set the sprite position to the body position and rotate the sprite to rotate the body converted to degrees. You may also need to rotate it 180 degrees (if your model is upside down) 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 complete example, consider this example that I created: https://github.com/viblo/pymunk/blob/master/examples/using_sprites_pyglet.py

(Im the author of the post)

+4
source

All Articles