在pygame中旋转矩形(不是图像) [英] Rotating a rectangle (not image) in pygame

查看:138
本文介绍了在pygame中旋转矩形(不是图像)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In pygame I use pygame.draw.rect(screen, color, rectangle) for all the rectangles in my program. I want to be able to rotate these rectangles to any angle. I have seen the following code to rotate IMAGES but my question is with RECTANGLES.

pygame.transform.rotate(image, angle)

但我正在处理矩形,我没有可以旋转的图像或表面".当我尝试使用

But I am working with rectangles, I don't have an image or "surface" that I can rotate. When I try to rotate a rectangle with

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

This gives TypeError: must be pygame.Surface, not pygame.Rect on the line with .rotate()

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

My question is, how can I rotate a and display a RECTANGLE(x,y,w,h), not an image, in pygame.

可能重复"的链接帖子不是重复的.一个答案解释了旋转矩形的后果,另一个使用代码来旋转图像.

The linked post that this is a "potential duplicate" of is not a duplicate. One answer explains about the consequences of rotating a rectangle and the other uses code for rotating an image.

推荐答案

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

See the second answer here: Rotating a point about another point (2D)

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

I think rectangles can only be horiz or vertical in their oreintation. You need to define the corners and rotate them and then draw and fill between them.

另一种方式是创建一个类

The other way is to make a class

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)

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

and use that instead, as then you will be able to rotate it using the transform function.

这篇关于在pygame中旋转矩形(不是图像)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆