Python 如何使pygame中的图像在旋转时保持静止?
所以我试着让一个图像始终指向鼠标,这有点奏效。图像指向鼠标,但它移动了一点。我不知道这是否是一个问题的形象或东西,但任何帮助将不胜感激。万一你不知道,方向是通过计算鼠标位置和图像位置之间的差值,运行atan函数,除以6.28,然后乘以360来计算的。这将导致鼠标从图像中移动的程度。这是密码。另外,我应该将图像的开发者归为属性,所以这里。由…制成的图标Python 如何使pygame中的图像在旋转时保持静止?,python,image,pygame,rotation,sprite,Python,Image,Pygame,Rotation,Sprite,所以我试着让一个图像始终指向鼠标,这有点奏效。图像指向鼠标,但它移动了一点。我不知道这是否是一个问题的形象或东西,但任何帮助将不胜感激。万一你不知道,方向是通过计算鼠标位置和图像位置之间的差值,运行atan函数,除以6.28,然后乘以360来计算的。这将导致鼠标从图像中移动的程度。这是密码。另外,我应该将图像的开发者归为属性,所以这里。由…制成的图标 如果以直角以外的任何角度旋转图像,pygame看起来会移动图像。要解决这个问题,您必须跟踪图像的上一个中心位置,并在每一帧更新它。试着这样做: c
如果以直角以外的任何角度旋转图像,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()
输出
只需更改:
win.blit(car\u rotated,car\u rotated.get\u rect(center=(carx,cary))
。我建议阅读以上问题的答案。请注意角度的计算是错误的。角度由atan2(y,x)
计算(而不是atan2(x,y)
)。投稿人无视我的建议,交换了sin
和cos
。通过交换sin
和cos
来补偿此错误,用另一个错误补偿一个错误。看见
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()