【问题标题】:Pygame make sprite walk in given rotationPygame让精灵在给定的旋转中行走
【发布时间】:2021-02-27 19:42:20
【问题描述】:

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

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

这是我的 Scratch 代码:

这是我的 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)

【问题讨论】:

    标签: python python-3.x pygame mit-scratch


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-11-25
      • 2023-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      相关资源
      最近更新 更多