【问题标题】:What does get_rect() do in the following program? Why was it used?get_rect() 在下面的程序中做了什么?为什么使用它?
【发布时间】:2018-07-28 07:54:21
【问题描述】:

我在这里浏览了一个教程 - www.raywenderlich.com/24252/beginning-game-programming-for-teens-with-python。在第 4 步中,他使用了以下语句:

# 6.1 - Set player position and rotation
position = pygame.mouse.get_pos()
angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26))
playerrot = pygame.transform.rotate(player, 360-angle*57.29)
playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2)
screen.blit(playerrot, playerpos1) 

他到底做了什么?他为什么这样做?

【问题讨论】:

  • pygame 文档中您可以阅读 Surface.get_rect 的描述:获取 Surface 的矩形区域(参见 here)。
  • 请发minimal, complete example,我们可以复制、运行和测试。

标签: python pygame


【解决方案1】:

您传递给pygame.Surface.blit 的坐标是左上角的坐标。我认为第 4 步中的 playerpos 应该是图像/表面的中心位置,因此您需要减去表面的一半宽度和一半高度才能获得左上角坐标(您想要将其 blit 的位置)。作者使用pygame.Surface.get_rect方法得到一个rect与旋转表面的宽度和高度,但他也可以使用pygame.Surface.get_width.get_height方法。

每次旋转后,playerrot 表面会有不同的大小,所以你需要再次调用get_rect 方法来获得一个新的矩形,其宽度和高度都更新了,你需要调整坐标。


顺便说一句,在这一行中添加3226 似乎会导致旋转出现问题。

angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26))

这应该可以正常工作:

angle = math.atan2(position[1]-playerpos[1], position[0]-playerpos[0])

也可以使用 pygame.Rect 作为 blit 位置,因此您可以这样做以创建一个具有旋转表面大小的矩形,并将 playerpos 作为 center 坐标:

playerpos1 = playerrot.get_rect(center=playerpos)

【讨论】:

  • 谢谢!顺便说一句,我也没有在我的代码中添加 32 和 26,因为我一直不明白作者为什么这样做。
【解决方案2】:

我认为 get_rect() 是一种获取矩形对象的方法,然后他获取其宽度属性来计算下一个玩家的位置。我猜这个方法是在代码中的某个地方定义的。也许也可以查看其余代码。

【讨论】:

    【解决方案3】:

    他使用它作为计算兔子旋转运动的一种方法,方法是获取兔子图像的矩形并将其分成两半以获得兔子位置的 (x, y) 变化:

    ------                                        ---------
    |X   |    ---->  Rotate 90 degrees   ---->    |      X|
    |    |                                        |       |
    ------                                        ---------
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 2020-01-29
      • 2013-01-14
      • 1970-01-01
      • 2013-02-08
      • 2016-02-14
      相关资源
      最近更新 更多