问题描述
因此,我一直在尝试使图像指向鼠标,并且它可以正常工作。图像指向鼠标,但略有移动。我不知道这是图像问题还是其他问题,但是可以提供任何帮助。万一您不知道,方向是通过获取鼠标pos与图像pos之间的差,通过atan函数运行,将其除以6.28,然后乘以360来计算的。这将得出鼠标的度数它来自图像。这是代码。另外,我应该归因于图像的开发者,所以在这里。 mynamepong来自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)
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()
解决方法
您需要设置汽车中心,然后围绕该点旋转汽车。
尝试以下代码:
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)
# 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()
输出
,如果以除直角以外的任何角度旋转图像,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)
当我测试代码时,它看起来好像在正确地旋转,但是由于某种原因,它看起来仍然有些怪异。让我知道这是您要去的吗。