3

I am creating a game and i need to rotate the ship, how can i rotate the ship from the center rather than the top left corner? I am using python 2.7 and Pygame 1.9.

Here is the code that i already have to rotate the image.

shipImg = pygame.transform.rotate(shipImg,-90)

However this rotates the image from the corner.

Ruarri
  • 105
  • 1
  • 2
  • 11
  • dude!!! go to sleep work tomorrow. :P – aaveg Oct 03 '15 at 03:19
  • it is 4:30 pm. It was last night that I was struggling to think and with all the code in my head i couldn't figure it out today either. That is why i posted the question today. – Ruarri Oct 03 '15 at 03:29
  • are you looking for arbitrary angle rotation or just 90 degree? – aaveg Oct 03 '15 at 03:38
  • If i did arbitrary angles then i would have to do more complex code for the bullets so for now i think i might stick to just 90 degrees. – Ruarri Oct 03 '15 at 03:41
  • after the rotation just shift the image coordinates such that the center overlaps after rotation. – aaveg Oct 03 '15 at 03:42

1 Answers1

2

Rotate the sprite then set the center of the new rect to the center of the old rect. This way the new one has the same center when you're done, making it look like it rotated around the center.

Here's an example function from the pygame wiki:

def rot_center(image, rect, angle):
    """rotate an image while keeping its center"""
    rot_image = pygame.transform.rotate(image, angle)
    rot_rect = rot_image.get_rect(center=rect.center)
    return rot_image,rot_rect

And here's how you would use it in your example:

# Draw ship image centered around 100, 100
oldRect = shipImg.get_rect(center=(100,100)) 
screen.blit(shipImg, oldRect) 

# Now  rotate the ship and draw it with the new rect, 
# which will keep it centered around 100,100
shipImg, newRect = rot_center(shipImg,oldRect,-90)
screen.blit(shipImg, newRect) 
Caleb Mauer
  • 662
  • 6
  • 11
  • What does it mean by rect in the line: def rot_center(image, rect, angle): – Ruarri Oct 03 '15 at 04:24
  • It means the rect of the thing you're rotating. Rects describe the position and dimension of the object. You can use [get_rect](https://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_rect) to get the rect from your image. rot_center needs the original rect so it can center the new rect of the rotated object. Also, see [rect documentation](http://pygame.org/docstest/ref/rect.html). – Caleb Mauer Oct 03 '15 at 14:34