Kea*_*nge 5 python pygame rotation rectangles
在pygame中,我pygame.draw.rect(screen, color, rectangle)在程序中使用了所有矩形。我希望能够将这些矩形旋转到任意角度。我已经看到以下代码来旋转图像,但是我的问题是RECTANGLES。
pygame.transform.rotate(image, angle)
Run Code Online (Sandbox Code Playgroud)
但是我正在使用矩形,但是我没有可以旋转的图像或“表面”。当我尝试旋转一个矩形
rect = pygame.draw.rect(screen, self.color, self.get_rectang())
rotatedRect = pygame.transform.rotate(rect, self.rotation)
screen.blit(rotatedRect)
Run Code Online (Sandbox Code Playgroud)
这给出TypeError: must be pygame.Surface, not pygame.Rect了.rotate()
我的问题是,如何(x,y,w,h)在pygame中旋转a并显示RECTANGLE 而不是图像。
这是“潜在重复项”的链接文章不是重复项。一个答案解释了旋转矩形的后果,另一个答案使用代码旋转图像。
小智 6
请参阅此处的第二个答案:Rotating a point about another point (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)
Run Code Online (Sandbox Code Playgroud)
并使用它,因为这样您就可以使用变换功能旋转它。
小智 5
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10224 次 |
| 最近记录: |