簡體   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