Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

python - How to turn the sprite in pygame while moving with the keys

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 Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: 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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...