python - 如何在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 奇怪地旋转,目前我找不到任何东西。
解决方案
您需要将旋转图像的边界矩形的中心设置为原始图像的边界矩形的中心。对图像使用旋转的矩形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)
推荐阅读
- javascript - 将变量的名称存储在数组中
- c++ - C ++中的CSV文件处理
- node.js - 如何使用节点 js 查找 .exe 文件路径
- python - 使用 xarray (pcolormesh) 绘制 2D 数据,同时保持纵横比
- java - 如何在gridLayout中以编程方式设置列号和行号?
- r - RShiny 分支连续输入
- swift - 从后台返回时更新标签
- python - 有问题的旧 python 脚本
- python - 在 Python 中查找函数的逆函数(可能使用 SymPy)
- java - 使用 gson 为 WebClient 设置自定义编码器/解码器或 typeAdapter