如何在用按键移动的同时在 pygame 中转动精灵 [英] How to turn the sprite in pygame while moving with the keys
本文介绍了如何在用按键移动的同时在 pygame 中转动精灵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以基本上我一直希望可以有效地转动你的精灵,同时用 WASD.任何想法,因为我肯定难倒,谢谢!
解决方案
参见
导入pygamepygame.init()窗口 = pygame.display.set_mode((500, 500))时钟 = pygame.time.Clock()car = pygame.image.load('CarRed64.png')位置 = pygame.math.Vector2(window.get_rect().center)方向 = pygame.math.Vector2(5, 0)运行 = 真运行时:时钟滴答(60)对于 pygame.event.get() 中的事件:如果 event.type == pygame.QUIT:运行 = 错误键 = pygame.key.get_pressed()如果键[pygame.K_w]:位置 += 方向如果键[pygame.K_s]:位置 -= 方向如果键[pygame.K_a]:direction.rotate_ip(-1)如果键[pygame.K_d]:direction.rotate_ip(1)window.fill(0)角度 = direction.angle_to((1, 0))旋转汽车 = pygame.transform.rotate(汽车,角度)window.blit(rotated_car,rotated_car.get_rect(center = (round(position.x), round(position.y))))pygame.display.flip()pygame.quit()出口()
So basically ive been hoping it would be possible to effectively turn your sprite while moving it around with WASD. Any ideas because im certainly stumped, thanks!
解决方案
See How do I rotate an image around its center using PyGame? for rotating a surface. If you want to rotate an image around a center point (cx, cy) you can just do that:
rotated_car = pygame.transform.rotate(car, angle)
window.blit(rotated_car, rotated_car.get_rect(center = (cx, cy))
Use pygame.math.Vector2
to store the position
and the direction
of movement. Change the position
by the current direction
when w respectively s is pressed. Change the angle of the direction
vector with rotate_ip
, when a respectively d is pressed:
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)
See also:
Minimal example:
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()
这篇关于如何在用按键移动的同时在 pygame 中转动精灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文