微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在 Pygame 中获取旋转图像的旋转矩形

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

矩形不是我想要的。

我看到我可以用精灵类来做到这一点。但我不想使用精灵。 我不明白 Sprite Rect 和 Image Rect 的区别。

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

图像是rotationed图像。

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

解决方法

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",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,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,window_center,angle)
    pygame.display.flip()

pygame.quit()
exit()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?