繁体   English   中英

如何在 Pygame 中为对象或精灵的位置设置动画并将其移动到预定义的位置或沿定义的路径移动?

[英]How to animate the position of an object or sprite in Pygame and move it towards predefined positions or along a defined path?

我学会了如何在pygame中打印图像,但我不知道如何制作动态位置(它可以自行改变图像位置)。 我错过了什么? 这是我的尝试。

import pygame

screen_size = [360,600]
screen = pygame.display.set_mode(screen_size)
background = pygame.image.load("rocketship.png")
keep_alive = True
while keep_alive:
    planet_x = 140
    o = planet_x
    move_direction = 'right'
    if move_direction == 'right':
          while planet_x == 140 and planet_x < 300:
            planet_x = planet_x + 5
          if planet_x == 300:
            planet_x = planet_x - 5
            while planet_x == 0:
                if planet_x == 0:
               
    planet_x+=5
   
    screen.blit(background, [planet_x, 950])
   
    pygame.display.update()

您不需要嵌套循环来为对象设置动画。 您有一个循环,即应用程序循环。 用它。 您需要在每一帧中重新绘制整个场景。 在每一帧中稍微改变对象的位置,因为对象在每一帧中被绘制在不同的位置。 物体似乎在平稳地移动。
定义对象应沿点列表移动的路径,并将对象从一个点移动到另一个点。

最小的例子

import pygame

pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

corner_points = [(100, 100), (300, 300), (300, 100), (100, 300)]
pos = corner_points[0]
speed = 2

def move(pos, speed, points):
    direction = pygame.math.Vector2(points[0]) - pos
    if direction.length() <= speed:
        pos = points[0]
        points.append(points[0])
        points.pop(0)
    else:
        direction.scale_to_length(speed)
        new_pos = pygame.math.Vector2(pos) + direction
        pos = (new_pos.x, new_pos.y) 
    return pos

image = pygame.image.load('bird.png').convert_alpha()

run = True
while run:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    pos = move(pos, speed, corner_points)
    image_rect = image.get_rect(center = pos)
           
    window.fill(0)
    pygame.draw.lines(window, "gray", True, corner_points) 
    window.blit(image, image_rect)
    pygame.display.update()

pygame.quit()
exit()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM