简体   繁体   中英

Rectangle Rotation in 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)

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

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.

Maybe this can help you:

#load image
image1 = pygame.image.load(file)
#get width and height of unrotated image
width1,height1 = image1.get_size()
#rotate image
image2 = pygame.transform.rotate(image1, angle)
#get width,height of rotated image
width2,height2 = image2.get_size()
#blit rotated image (positon - difference of width or height /2)
display.blit(image2,[round(x - (width1 - width2)/2),round(y - (height1 - height2)/2)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM