我试图移动一个角色,以便在我移动它时它们面向鼠标;我理解这个概念,但我完全不知道如何编码。目前,我了解如何单独旋转角色以及如何分别移动角色。我可以将两者合并,以便我可以用键和鼠标移动和旋转我的角色吗?
这些是我定义的变量:
xPlayer = 25
yPlayer = 25
dxPlayer = 0
dyPlayer = 0
playerPosition = (25,25)
这是允许图像沿鼠标方向旋转的部分:
go = True
while go:
position = pygame.mouse.get_pos()
screen.blit(nightBackground, (0,0))
mousePosition = pygame.mouse.get_pos()
angle = math.atan2(mousePosition[1]-(playerPosition[1]+32),mousePosition[0]-(playerPosition[0]+26))
playerRotate = pygame.transform.rotate(peterPlayer, 360-angle*57.29)
playerpos1 = (playerPosition[0]-playerRotate.get_rect().width/2, playerPosition[1]-playerRotate.get_rect().height/2)
screen.blit(playerRotate, playerpos1)
pygame.display.update()
这是用键控制我的角色的部分:
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
dxPlayer = -15
elif event.key == pygame.K_RIGHT:
dxPlayer = 15
elif event.key == pygame.K_UP:
dyPlayer = -15
elif event.key == pygame.K_DOWN:
dyPlayer = 15
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
dxPlayer = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
dyPlayer = 0
xPlayer = xPlayer + dxPlayer
yPlayer = yPlayer + dyPlayer
pygame.display.update()
非常感谢任何帮助!