如何使 pygame 中的图像在旋转时保持静止?

How to make an image in pygame stay still when rotated?

所以我试图让图像始终指向鼠标,并且它有点管用。图像指向鼠标,但它移动了一点。我不知道这是图像问题还是其他问题,但我们将不胜感激。以防万一你不知道,方向是通过计算鼠标位置和图像位置之间的差异,运行 通过 atan 函数将其除以 6.28,然后乘以 360。这将导致你的鼠标从图像上的角度。这是代码。另外,我应该归因于图像的开发者,所以在这里。 mynamepong from www.flaticon.com

制作的图标
import pygame
import math
pygame.init()
win_height=800
win_width=800
win=pygame.display.set_mode((win_width,win_height))
pygame.display.set_caption("Rotation Test")

black=(0,0,0)

carx=200
cary=200

clock=pygame.time.Clock()
car=pygame.image.load("inkscape images for games/car.png")
car=pygame.transform.scale(car,(100,100))

while True:
    mouse=pygame.mouse.get_pos()
    clock.tick(60)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
    angle=math.atan2(mouse[0]-carx,mouse[1]-cary)/6.28*360
    win.fill(black)
    car_rotated=pygame.transform.rotate(car,angle)
    win.blit(car_rotated,(carx,cary))
    pygame.display.update()

看起来 pygame 如果您以任何角度旋转图像而不是直角,它会移动图像。要解决这个问题,您必须跟踪图像的先前中心位置并在每一帧更新它。尝试这样的事情:

car_rotated=pygame.transform.rotate(car,angle)
new_rect = car_rotated.get_rect(center = car.get_rect().center)
win.blit(car_rotated,new_rect)

代码在我测试时看起来旋转正确,但由于某种原因它看起来还是有点奇怪。让我知道这是否是您想要的。

您需要设置汽车中心然后围绕该点旋转汽车。

试试这个代码:

import pygame
import math
pygame.init()
win_height=800
win_width=800
win=pygame.display.set_mode((win_width,win_height))
pygame.display.set_caption("Rotation Test")

black=(0,0,0)

# center of car rect
carx=400
cary=400

clock=pygame.time.Clock()
car=pygame.image.load("inkscape images for games/car.png")
car=pygame.transform.scale(car,(100,100))

while True:
    mouse=pygame.mouse.get_pos()
    clock.tick(60)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()

    angle=math.atan2(mouse[0]-carx,mouse[1]-cary)/6.28*360-90
    win.fill(black)
    car_rotated=pygame.transform.rotate(car,angle)
    new_rect = car_rotated.get_rect(center = (carx, cary))
    win.blit(car_rotated,(new_rect.x,new_rect.y))
    pygame.display.update()

输出