【问题标题】:How to turn the sprite in pygame while moving with the keys如何在使用键移动时在pygame中转动精灵
【发布时间】:2020-11-11 18:53:40
【问题描述】:

所以基本上我一直希望可以有效地转动你的精灵,同时用 WASD 移动它。任何想法,因为我肯定很难过,谢谢!

【问题讨论】:

  • @JamesHuang “你必须做一些数学运算才能让它围绕中心” - 这是微不足道的。查看答案。
  • @Rabbid76 了解基本概念,谢谢!

标签: python pygame sprite turn pygame-surface


【解决方案1】:

请参阅How do I rotate an image around its center using PyGame? 以了解旋转表面。如果您想围绕中心点(cxcy)旋转图像,您可以这样做:

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

使用pygame.math.Vector2 存储运动的positiondirection。当按下 ws 时,将 position 更改为当前的 direction。当分别按下 ad 时,用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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多