簡體   English   中英

Python / Pygame中的矩形旋轉

[英]Rectangle Rotation in Python/Pygame

嘿,我試圖繞其中心旋轉一個矩形,當我嘗試旋轉該矩形時,它同時向上和向左移動。 有人對如何解決這個問題有任何想法嗎?

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的內部功能不適用於旋轉的矩形,是嗎?

除非您有使用新矩形角編寫的代碼,否則這樣做是要定義一個新矩形,其邊平行於“曲面”邊緣,在旋轉時可以將原始矩形切入其中,而不是在矩形上與原始尺寸相同,但傾斜角度相同。 旋轉后向其傳遞“ self.collideRect”對象的任何Pygame函數都將做到這一點:將矩形視為與曲面對齊,就好像它是用現在的拐角創建的一樣。

如果您的代碼要求您在旋轉的矩形內檢查甚至繪制,則必須在旋轉之前執行所有計算,並僅在顯示所需內容時執行坐標旋轉。 也就是說,您將使用在渲染的最后一步中應用的全局坐標變換。

也許這可以幫助您:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM