Skip to main content
 首页 » 编程设计

python之如何在pycharm中从中心旋转一个对象

2024年11月01日7JeffreyZhao

我试图在 pycharm 中旋转图像,由于某种原因,当我旋转时,对象会摇晃并且不会旋转到位。

class rocket(object): 
def __init__(self, x, y): 
    self.original_image = pygame.image.load('sprites/spaceship-off.png') 
    self.image = self.original_image 
    self.x = x 
    self.y = y 
    self.width = 50 
    self.height = 50 
    self.speed = 15 
    self.angle = 0 
    self.direction = [0, -1] 
    self.position = [400, 400] 
 
def draw(self, win): 
    win.blit(self.image, (self.position)) 
    self.image = pygame.transform.rotate(self.original_image, self.angle) 

-

if keys[pygame.K_a] and player.x > player.speed: 
    player.angle += 10 % 360 
if keys[pygame.K_d] and player.x < 800 - player.width - player.speed: 
    player.angle -= 10 % 360 

请您参考如下方法:

当您想围绕图像的中心旋转图像时,您必须:

  • 获取枢轴(即未旋转图像的中心点)
  • 旋转图像并得到旋转图像的(轴对齐边界)矩形
  • 将矩形居中于轴心
  • blit 新矩形左上角的图像
def draw(self, win): 
 
    image_rect = self.original_image.get_rect(topleft = self.position) 
    pivot = image_rect.center 
 
    self.image = pygame.transform.rotate(self.original_image, self.angle) 
    rotated_rect = self.image.get_rect(center = pivot) 
 
    win.blit(self.image, rotated_rect.topleft) 

另见 How do I rotate an image around its center using Pygame?