微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决Pygame 让精灵在给定的旋转中行走

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

有很多示例显示图像的旋转,但我想知道如何更改精灵的旋转以使其沿给定方向移动,而无需更改图像。

这是我的 Scratch 代码

Scratch code (set rotation style : don't rotate,point in direction 120,move 10 steps.)

这是我的 Pygame 精灵类:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。