0

Currently, I am trying to get my gun to rotate to look towards my mouse - which I have working. However the rotation is just odd and doesn't work how I want it to. I am trying to rotate it with a center of (0,0) so that it rotates around that top left corner, however it just doesn't seem to want to clamp the top left in one position and rotate around it.

What I have:

class Gun():
def __init__(self):
    self.original_image = p.transform.scale(p.image.load('D:\Projects\platformer\Assets\Gun.png'),(20,8))
def rotate(self,x,y):
    mx,my = p.mouse.get_pos()
    rel_x,rel_y = mx - x,my - y
    angle = (180/math.pi) * -math.atan2(rel_y,rel_x)
    self.image = p.transform.rotate(self.original_image,int(angle))
    self.rect = self.image.get_rect(center=(0,0))

    WIN.blit(self.image,(x,y))

This is what is happening

yet I would want the top left of the gun to stick in just one position. Like this:

Any suggestions on how to do this, because I understand that pygame rotates weirdly and nothing I can find currently works.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
B1ake
  • 11
  • 5

1 Answers1

0

You need to set the center of the bounding rectangle of the rotated image with the center of the bounding rectangle of the original image. Use the rotated rectangle to blit the image:

self.image = p.transform.rotate(self.original_image,int(angle))
self.rect = self.original_image.get_rect(topleft = (x, y))

rot_rect = self.image.get_rect(center = self.rect.center)
WIN.blit(self.image, rot_rect)

See also How do I rotate an image around its center using PyGame?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174