在pygame中旋转一个矩形(不是图像)

新手上路,请多包涵

在 pygame 中,我对程序中的所有矩形使用 pygame.draw.rect(screen, color, rectangle) 。我希望能够将这些矩形旋转到任意角度。我看过以下代码来旋转 IMAGES 但我的问题是 RECTANGLES

 pygame.transform.rotate(image, angle)

但是我正在使用矩形,我没有可以旋转的图像或“表面”。当我尝试旋转一个矩形时

rect = pygame.draw.rect(screen, self.color, self.get_rectang())
rotatedRect = pygame.transform.rotate(rect, self.rotation)
screen.blit(rotatedRect)

这给出了 TypeError: must be pygame.Surface, not pygame.Rect 与 .rotate()

我的问题是,如何在 pygame 中旋转 a 并显示 RECTANGLE (x,y,w,h) 而不是图像。

这是“潜在重复”的链接帖子不是重复的。一个答案解释了旋转矩形的后果,另一个答案使用旋转图像的代码。

原文由 Keatinge 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

在这里查看第二个答案: 围绕另一个点旋转一个点(2D)

我认为矩形的定位只能是水平或垂直的。您需要定义角并旋转它们,然后在它们之间绘制和填充。

另一种方法是上课

class myRect(pygame.Surface):
    def __init__(self, parent, xpos, ypos, width, height):
      super(myRect, self).__init__(width, height)
      self.xpos = xpos
      self.ypos = ypos
      self.parent = parent

    def update(self, parent):
      parent.blit(self, (self.xpos, self.ypos))

    def rotate(self, angle):
      #(your rotation code goes here)

并改用它,因为这样您就可以使用变换功能旋转它。

原文由 marienbad 发布,翻译遵循 CC BY-SA 3.0 许可协议

import pygame as py

# define constants
WIDTH = 500
HEIGHT = 500
FPS = 30

# define colors
BLACK = (0 , 0 , 0)
GREEN = (0 , 255 , 0)

# initialize pygame and create screen
py.init()
screen = py.display.set_mode((WIDTH , HEIGHT))
# for setting FPS
clock = py.time.Clock()

rot = 0
rot_speed = 2

# define a surface (RECTANGLE)
image_orig = py.Surface((100 , 100))
# for making transparent background while rotating an image
image_orig.set_colorkey(BLACK)
# fill the rectangle / surface with green color
image_orig.fill(GREEN)
# creating a copy of orignal image for smooth rotation
image = image_orig.copy()
image.set_colorkey(BLACK)
# define rect for placing the rectangle at the desired position
rect = image.get_rect()
rect.center = (WIDTH // 2 , HEIGHT // 2)
# keep rotating the rectangle until running is set to False
running = True
while running:
    # set FPS
    clock.tick(FPS)
    # clear the screen every time before drawing new objects
    screen.fill(BLACK)
    # check for the exit
    for event in py.event.get():
        if event.type == py.QUIT:
            running = False

    # making a copy of the old center of the rectangle
    old_center = rect.center
    # defining angle of the rotation
    rot = (rot + rot_speed) % 360
    # rotating the orignal image
    new_image = py.transform.rotate(image_orig , rot)
    rect = new_image.get_rect()
    # set the rotated rectangle to the old center
    rect.center = old_center
    # drawing the rotated rectangle to the screen
    screen.blit(new_image , rect)
    # flipping the display after drawing everything
    py.display.flip()

py.quit()

原文由 Ashish kumar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题