gpt4 book ai didi

python - Pygame 图像旋转

转载 作者:太空宇宙 更新时间:2023-11-03 16:43:54 25 4
gpt4 key购买 nike

我正在使用 Python 和 Pygame 制作一个简单的程序自上而下的驾驶模拟器。传动部分工作正常;向上键移动汽车,左右键驾驶汽车。问题出在图像的旋转上;它到处移动(运行代码来查看它)。我认为这是因为当图像旋转时,大小发生了变化(因为它必须是矩形)。当分辨率改变时,位置也会改变。如果有人知道解决这个问题的方法,我将非常感激。car.png --> enter image description here

import pygame, math
pygame.init()

screen = pygame.display.set_mode((600, 500))
clock = pygame.time.Clock()
pygame.display.set_caption('Car Driving')

def main():
r = 0
car = pygame.image.load('images/car.png')

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()

r += 3

screen.fill((40,40,40))
screen.blit(pygame.transform.rotate(car, r), (200, 100))

pygame.display.update()
clock.tick(40)


main()

最佳答案

来自 PYgame 文档:

Unless rotating by 90 degree increments, the image will be padded larger to hold the new size.

这意味着你得到了一个新的 Rect 对象。文档中没有任何信息,但我认为原始图像将位于新矩形的中心。
这意味着如果您将新矩形的位置放置到所需的位置,您将获得预期的结果。

center=(100,200) #Store pos by center

#In loop:
rCar=pygame.transform.rotate(car,r) #Do the rotation
size=rCar.get_size() #Store size
hSize=[n/2 for n in size] #Half the size
pos=(center[0]-hSize[0],center[1]-hSize[1]) #Substract half the size
#from the center
screen.blit(rCar,pos) #Draw

让我解释一下:

enter image description here

希望对你有帮助。

关于python - Pygame 图像旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36521876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com