首页 > 解决方案 > 如何在pygame中旋转左上角的东西

问题描述

目前,我正试图让我的枪旋转以看向我的鼠标——我正在工作。然而,旋转只是奇怪的,并没有按照我想要的方式工作。我试图以(0,0)的中心旋转它,以便它围绕左上角旋转,但是它似乎不想将左上角夹在一个位置并围绕它旋转。

我有的:

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))

这就是正在发生的事情

但我希望枪的左上角只停留在一个位置。像这样:

关于如何做到这一点的任何建议,因为我知道 pygame 奇怪地旋转,目前我找不到任何东西。

标签: pythonpython-3.xpygamerotationimage-rotation

解决方案


您需要将旋转图像的边界矩形的中心设置为原始图像的边界矩形的中心。对图像使用旋转的矩形blit

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)

另请参阅如何使用 PyGame 围绕其中心旋转图像?


推荐阅读