python - 在 Pygame 中获取旋转图像的旋转矩形

标签 python pygame pygame-surface

我有一个关于 pygame rect 的问题。

矩形不是我想要的。

我发现我可以用 Sprite 类来做到这一点。但我不想使用 Sprite 。 我不明白Sprite 矩形和图像矩形的区别。

I want to get rect like this

But I am getting like this

这是我的矩形函数:

def getRect(self):
    return self.image.get_rect(center=(self.x,self.y))

图像是旋转图像。

我的英语不太好,我已经尽可能告诉你了。

最佳答案

get_rect()返回 pygame.Rect目的。 pygame.Rect 存储位置和大小。它始终是轴对齐的,并且不能表示旋转的矩形。

使用pygame.math.Vector2.rotate()计算旋转矩形的角点。 orig_image 是旋转之前的图像:

rect = orig_image.get_rect(center = (self.x, self.y))

pivot = pygame_math.Vector2(self.x, self.y)

p0 = (pygame.math.Vector2(rect.topleft) - pivot).rotate(-angle) + pivot 
p1 = (pygame.math.Vector2(rect.topright) - pivot).rotate(-angle) + pivot 
p2 = (pygame.math.Vector2(rect.bottomright) - pivot).rotate(-angle) + pivot 
p3 = (pygame.math.Vector2(rect.bottomleft) - pivot).rotate(-angle) + pivot 

使用pygame.draw.lines()绘制旋转的矩形:

pygame.draw.lines(screen, (255, 255, 0), True, [p0, p1, p2, p3], 3)

另请参阅How do I rotate an image around its center using PyGame?How can you rotate an image around an off center pivot in PyGame .


最小示例: repl.it/@Rabbid76/PyGame-RotatedRectangle

import pygame

pygame.init()
window = pygame.display.set_mode((400, 400))
font = pygame.font.SysFont(None, 50)
clock = pygame.time.Clock()

orig_image = font.render("rotated rectangle", True, (255, 0, 0))
angle = 30
rotated_image = pygame.transform.rotate(orig_image, angle)

def draw_rect_angle(surf, rect, pivot, angle):
    pts = [rect.topleft, rect.topright, rect.bottomright, rect.bottomleft]
    pts = [(pygame.math.Vector2(p) - pivot).rotate(-angle) + pivot for p in pts]
    pygame.draw.lines(surf, (255, 255, 0), True, pts, 3)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False    

    window.fill(0)
    window_center = window.get_rect().center
    window.blit(rotated_image, rotated_image.get_rect(center = window_center))
    rect = orig_image.get_rect(center = window_center)
    draw_rect_angle(window, rect, window_center, angle)
    pygame.display.flip()

pygame.quit()
exit()

关于python - 在 Pygame 中获取旋转图像的旋转矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66984521/

相关文章:

python - 我如何在pygame中删除我的 Sprite 表上的黑色背景

Python倒计时

python - win.blit()后台pygame时出现滞后

python - 在 Django 中将 Postgres 与 Oscar 同步时出现编程错误

python - “pygame 错误”: font not initialized.。在已使用的字体上?

python - 安装旧版本的 scikit-learn

python - 特定的 .wav 文件被缩短和扭曲

python - 为什么pygame blit不能在类里面工作

Python Socket 编程简单的 Web 服务器,尝试从服务器访问 html 文件

BeautifulSoup、requests 和 lxml 的 Python 解码错误