【问题标题】:How can i rotate an image from the center rather than the corner in pygame? [duplicate]如何在pygame中从中心而不是角落旋转图像? [复制]
【发布时间】:2015-12-31 08:03:07
【问题描述】:

我正在创建一个游戏,我需要旋转船,我怎样才能从中心而不是左上角旋转船?我正在使用 python 2.7 和 Pygame 1.9。

这是我已经必须旋转图像的代码。

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

但是,这会从角落旋转图像。

【问题讨论】:

  • 老兄!!!明天睡觉上班。 :P
  • 现在是下午 4:30。昨晚我一直在努力思考,而我脑海中的所有代码我今天也无法弄清楚。这就是我今天发布问题的原因。
  • 您是在寻找任意角度旋转还是仅 90 度?
  • 如果我做任意角度,那么我将不得不为子弹做更复杂的代码,所以现在我想我可能会坚持 90 度。
  • 旋转后只需移动图像坐标,使中心在旋转后重叠。

标签: python python-2.7 pygame


【解决方案1】:

旋转精灵,然后将新矩形的中心设置为旧矩形的中心。这样,当您完成后,新的中心具有相同的中心,使其看起来像围绕中心旋转。

这是来自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

以下是您在示例中使用它的方式:

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

【讨论】:

  • 直线中的rect是什么意思:def rot_center(image, rect, angle):
  • 这意味着你正在旋转的东西的矩形。矩形描述对象的位置和尺寸。您可以使用get_rect 从图像中获取矩形。 rot_center 需要原始矩形,因此它可以使旋转对象的新矩形居中。另请参阅rect documentation。
猜你喜欢
  • 2019-04-07
  • 2011-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
相关资源
最近更新 更多