Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i rotate an image from the center rather than the corner in pygame? [duplicate]

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.

like image 552
Ruarri Avatar asked Jan 24 '26 13:01

Ruarri


1 Answers

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) 
like image 111
Caleb Mauer Avatar answered Jan 27 '26 03:01

Caleb Mauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!