Search code examples
python-3.xpygamepython-3.7pygame-surface

"Merge" Multiple Images in Pygame into one Surface to rotate them all dynamically


Currently I'm working on a game in pygame which is inspired by a game called "recrew" (it was made on the global game jam 2020) The goal is to extend the ship, explore Islands and prevent your ship from sinking.

For a better feeling I wand to rotate the whole ship. The ship is represented as a class with all block saved into a list. Every block is a single pygame.Surface which gets rendered in the ship class. Is there a way to rotate all these Blocks dynamically so that instead of every block rotating and not changing Position the whole ship dynamically rotates.

Maybe the blocks could all be merged into a big Surface relative to their position or the part of the main Window Surface with the blocks gets saved onto another Surface. I just don't know a good way to solve this problem.


Solution

  • You can blit an image (which is just a Surface) onto any other surface, not just the display (see docs here). So you can create a merged surface and blit the boat image and each of the images that you want on the ship onto it. Like this:

    merged_surf.blit(some_surface, some_surface_rect)
    

    Where the position part of some_surface_rect describes where on the merged_surf you want to place it, so it is relative to that merged_surf.

    Then you can rotate that merged_surf with all the other images already on it (see docs here). Then finally blit that merged_surf onto the display.

    Remember that the bounding box of the rotated surface will likely be larger than that of the original image. If you are trying to keep the center in place you will need to assign the center of the rotated surfaces rect to the center of the original pre-rotated image. Otherwise it will appear to bounce around as it rotates.