Python/Pygame 中的矩形旋转 [英] Rectangle Rotation in Python/Pygame

查看:80
本文介绍了Python/Pygame 中的矩形旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在尝试围绕其中心旋转一个矩形,当我尝试旋转该矩形时,它同时向上和向左移动.有没有人对如何解决这个问题有任何想法?

Hey I'm trying to rotate a rectangle around its center and when I try to rotate the rectangle, it moves up and to the left at the same time. Does anyone have any ideas on how to fix this?

def rotatePoint(self, angle, point, origin):
    sinT = sin(radians(angle))
    cosT = cos(radians(angle))
    return (origin[0] + (cosT * (point[0] - origin[0]) - sinT * (point[1] - origin[1])),
                  origin[1] + (sinT * (point[0] - origin[0]) + cosT * (point[1] - origin[1])))

def rotateRect(self, degrees):
    center = (self.collideRect.centerx, self.collideRect.centery)
    self.collideRect.topleft = self.rotatePoint(degrees, self.collideRect.topleft, center)
    self.collideRect.topright = self.rotatePoint(degrees, self.collideRect.topright, center)
    self.collideRect.bottomleft = self.rotatePoint(degrees, self.collideRect.bottomleft, center)
    self.collideRect.bottomright = self.rotatePoint(degrees, self.collideRect.bottomright, center)

推荐答案

旋转代码看起来不错 - 但是,您知道 pygame 的内部结构不适用于旋转矩形,是吗?

The rotation code looks to be fine - but, you are aware that pygame's internals don't work with rotated rectangles, do you?

除非您自己编写了一些带有新矩形角的代码,否则它的作用是定义一个新矩形,其边平行于 Surface 边缘,原始矩形在旋转时可以内接于其中,而不是以倾斜角度与原始大小相同的矩形.任何在旋转后传递self.collideRect"对象的 Pygame 函数都会这样做:将矩形视为与表面对齐,就好像它是用现在的角创建的一样.

Unless you have some code you wrote yourself with the new rectangle corners, what this does is to define a new rectangle, with sides parallel to the Surface edges, where the original rectangle, when rotated, could be inscribed to, not a rectangle at the same size than the original at a skewed angle. Any Pygame function to which you pass the "self.collideRect" object after the rotation will just do that: treat the rectangle as aligned to the surface, just as if it has been created with the corners it has now.

如果您的代码要求您在旋转的矩形内检查或什至绘制内容,则必须按照旋转前的位置执行所有计算,并且仅在显示内容时执行坐标旋转想.也就是说,您使用全局坐标变换,该变换应用于渲染的最后一步.

If your code requires you to check for things, or even draw, inside a rotated rectangle, you have to perform all the calculations as they where prior to the rotation, and just perform the coordinate rotation at the time of displaying what you want. That is, you work with a global coordinate transform, that is applied in the last step of rendering.

这篇关于Python/Pygame 中的矩形旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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