Pygame 让精灵在给定的旋转中行走

Pygame make sprite walk in given rotation

很久以前我做了一个小脚本,我想用Pygame转换成Python。

有很多示例显示图像的旋转,但我想知道如何在不改变图像的情况下更改精灵的旋转以使其沿给定方向移动。

这是我的 Scratch 代码:

这是我的 Pygame 精灵 class:

class Star(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = img_star
        self.rect = self.image.get_rect()
        self.velocity = [0, 0]
        self.rect.x = random.randint(0, window_x)
        self.rect.y = random.randint(0, window_y)

使用 MOUSEBUTTONDOWN 事件检测何时单击鼠标:

if event.type == pygame.MOUSEBUTTONDOWN:
    mouse_x, mouse_y = event.pos

计算精灵中心到鼠标点击位置的向量:

dx = mouse_x - star.rect.centerx
dy = mouse_y - star.rect.centery

计算向量的长度 (Euclidean distance):

dist = math.sqrt(dx*dx + dy*dy)

dist = math.hypot(dx, dy)

规范化向量 (Unit vector)。归一化向量的长度为 1:

if dist > 0:
    dx /= dist
    dy /= dist

将对象沿矢量方向移动一定步数:

star.rect.x += steps * dx
star.rect.y += steps * dy

另见 Follow target or mouse


最小示例:

import pygame, random, math

class Star(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = img_star
        self.rect = self.image.get_rect()
        self.velocity = [0, 0]
        self.rect.x = random.randint(0, window_x)
        self.rect.y = random.randint(0, window_y)

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

img_star = pygame.Surface((20, 20), pygame.SRCALPHA)
pygame.draw.circle(img_star, (255, 255, 0), (10, 10), 10)
star = Star()
group = pygame.sprite.Group(star)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False          
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = event.pos
            dx = mouse_x - star.rect.centerx
            dy = mouse_y - star.rect.centery
            dist = math.sqrt(dx*dx + dy*dy)
            steps = 10
            if dist > 0:
                star.rect.x += steps * dx / dist
                star.rect.y += steps * dy / dist

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()