2012-01-20 62 views
1

嘿,我正試圖圍繞它的中心旋轉一個矩形,當我嘗試旋轉矩形時,它同時向上移動並向左移動。有沒有人有任何想法如何解決這個問題?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) 

回答

1

旋轉代碼看起來是很好 - 但是,大家都知道,pygame中的內部不旋轉的矩形工作,你呢?

除非你有一些代碼是用新的矩形邊角編寫的,否則它會定義一個新的矩形,其邊與邊表面平行,其中原始矩形旋轉時可以刻入,而不是一個與原始角度相同的矩形。任何在旋轉後傳遞「self.collideRect」對象的Pygame函數都可以做到這一點:將矩形對齊到曲面,就好像它已經用它現在的角落創建了一樣。

如果您的代碼要求您檢查事物,甚至在旋轉的矩形內繪製,則必須執行與旋轉之前相同的所有計算,並在顯示內容時執行座標旋轉你要。也就是說,你使用全局座標變換,這是在渲染的最後一步中應用的。

+1

所以你的意思是,如果我要檢查,看是否有在矩形內的碰撞,我不得不做出的一個副本矩形,然後每次從副本旋轉它?對不起,我只是很難理解這一點。 – mramazingguy

+1

對於任何未來碰到過這個問題的人......他說的是Pygame的引擎不理解旋轉的矩形。除了常規的未旋轉矩形之外,您無法對其進行碰撞檢測。 – atomictom

0

也許這可以幫助你:

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