如何在使用键移动时在pygame中打开精灵

问题描述

所以基本上我一直希望可以通过 W A S D来有效地旋转精灵。 。任何想法,因为我肯定很困惑,谢谢!

解决方法

有关旋转表面,请参见How do I rotate an image around its center using PyGame?。如果要围绕中心点旋转图像( cx cy ),可以执行以下操作:

rotated_car = pygame.transform.rotate(car,angle)
window.blit(rotated_car,rotated_car.get_rect(center = (cx,cy))

使用pygame.math.Vector2存储运动的positiondirection。分别按下 w s 时,将position更改为当前的direction。分别按下 a d 时,分别用rotate_ip更改direction向量的角度:

keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
    position += direction
if keys[pygame.K_s]:
    position -= direction
if keys[pygame.K_a]:
    direction.rotate_ip(-1)
if keys[pygame.K_d]:
    direction.rotate_ip(1)

另请参阅:


最小示例: repl.it/@Rabbid76/PyGame-CarMovement

import pygame
pygame.init()
window = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()

car = pygame.image.load('CarRed64.png')
position = pygame.math.Vector2(window.get_rect().center)
direction = pygame.math.Vector2(5,0)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        position += direction
    if keys[pygame.K_s]:
        position -= direction
    if keys[pygame.K_a]:
        direction.rotate_ip(-1)
    if keys[pygame.K_d]:
        direction.rotate_ip(1)

    window.fill(0)
    angle = direction.angle_to((1,0))
    rotated_car = pygame.transform.rotate(car,angle)
    window.blit(rotated_car,rotated_car.get_rect(center = (round(position.x),round(position.y))))
    pygame.display.flip()

pygame.quit()
exit()