由几张图片制作的动画精灵

2024-12-31 08:37:00
admin
原创
106
摘要:问题描述:我一直在寻找一些关于使用 Pygame 在 Python 中从几张图片制作简单精灵动画的优秀教程。我仍然没有找到我想要的东西。我的问题很简单:如何用几张图像制作动画精灵(例如:制作几张尺寸为 20x20px 的爆炸图像,使其成为一张动画)有什么好主意吗?解决方案 1:动画有两种类型:帧相关和时间相关...

问题描述:

我一直在寻找一些关于使用 Pygame 在 Python 中从几张图片制作简单精灵动画的优秀教程。我仍然没有找到我想要的东西。

我的问题很简单:如何用几张图像制作动画精灵(例如:制作几张尺寸为 20x20px 的爆炸图像,使其成为一张动画)

有什么好主意吗?


解决方案 1:

动画有两种类型:帧相关时间相关。两者的工作方式类似。


主循环之前

  1. 将所有图像加载到列表中。

  2. 创建三个变量:

1. `index`,跟踪图像列表的当前索引。
2. `current_time`或者`current_frame`跟踪自上次索引切换以来的当前时间或当前帧。
3. `animation_time`或者`animation_frames`定义在切换图像之前应经过多少秒或多少帧。

在主循环期间

  1. 增加current_time自上次增加以来经过的秒数,或增加current_frame1。

  2. 检查是否current_time >= animation_timecurrent_frame >= animation_frame。如果是,继续 3-5。

  3. 重置current_time = 0current_frame = 0

  4. 增加索引,除非它等于或大于图像数量。在这种情况下,重置index = 0

  5. 相应地改变精灵的图像。


完整的工作示例

import os
import pygame
pygame.init()

SIZE = WIDTH, HEIGHT = 720, 480
BACKGROUND_COLOR = pygame.Color('black')
FPS = 60

screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()


def load_images(path):
    """
    Loads all images in directory. The directory must only contain images.

    Args:
        path: The relative or absolute path to the directory to load images from.

    Returns:
        List of images.
    """
    images = []
    for file_name in os.listdir(path):
        image = pygame.image.load(path + os.sep + file_name).convert()
        images.append(image)
    return images


class AnimatedSprite(pygame.sprite.Sprite):

    def __init__(self, position, images):
        """
        Animated sprite object.

        Args:
            position: x, y coordinate on the screen to place the AnimatedSprite.
            images: Images to use in the animation.
        """
        super(AnimatedSprite, self).__init__()

        size = (32, 32)  # This should match the size of the images.

        self.rect = pygame.Rect(position, size)
        self.images = images
        self.images_right = images
        self.images_left = [pygame.transform.flip(image, True, False) for image in images]  # Flipping every image.
        self.index = 0
        self.image = images[self.index]  # 'image' is the current image of the animation.

        self.velocity = pygame.math.Vector2(0, 0)

        self.animation_time = 0.1
        self.current_time = 0

        self.animation_frames = 6
        self.current_frame = 0

    def update_time_dependent(self, dt):
        """
        Updates the image of Sprite approximately every 0.1 second.

        Args:
            dt: Time elapsed between each frame.
        """
        if self.velocity.x > 0:  # Use the right images if sprite is moving right.
            self.images = self.images_right
        elif self.velocity.x < 0:
            self.images = self.images_left

        self.current_time += dt
        if self.current_time >= self.animation_time:
            self.current_time = 0
            self.index = (self.index + 1) % len(self.images)
            self.image = self.images[self.index]

        self.rect.move_ip(*self.velocity)

    def update_frame_dependent(self):
        """
        Updates the image of Sprite every 6 frame (approximately every 0.1 second if frame rate is 60).
        """
        if self.velocity.x > 0:  # Use the right images if sprite is moving right.
            self.images = self.images_right
        elif self.velocity.x < 0:
            self.images = self.images_left

        self.current_frame += 1
        if self.current_frame >= self.animation_frames:
            self.current_frame = 0
            self.index = (self.index + 1) % len(self.images)
            self.image = self.images[self.index]

        self.rect.move_ip(*self.velocity)

    def update(self, dt):
        """This is the method that's being called when 'all_sprites.update(dt)' is called."""
        # Switch between the two update methods by commenting/uncommenting.
        self.update_time_dependent(dt)
        # self.update_frame_dependent()


def main():
    images = load_images(path='temp')  # Make sure to provide the relative or full path to the images directory.
    player = AnimatedSprite(position=(100, 100), images=images)
    all_sprites = pygame.sprite.Group(player)  # Creates a sprite group and adds 'player' to it.

    running = True
    while running:

        dt = clock.tick(FPS) / 1000  # Amount of seconds between each loop.

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    player.velocity.x = 4
                elif event.key == pygame.K_LEFT:
                    player.velocity.x = -4
                elif event.key == pygame.K_DOWN:
                    player.velocity.y = 4
                elif event.key == pygame.K_UP:
                    player.velocity.y = -4
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
                    player.velocity.x = 0
                elif event.key == pygame.K_DOWN or event.key == pygame.K_UP:
                    player.velocity.y = 0

        all_sprites.update(dt)  # Calls the 'update' method on all sprites in the list (currently just the player).

        screen.fill(BACKGROUND_COLOR)
        all_sprites.draw(screen)
        pygame.display.update()


if __name__ == '__main__':
    main()

何时选择哪一个

时间相关动画允许您以相同的速度播放动画,无论帧速率有多慢/多快或您的计算机有多慢/多快。这允许您的程序自由更改帧速率而不影响动画,并且即使计算机无法跟上帧速率,它也将保持一致。如果程序滞后,动画将赶上它应该处于的状态,就好像没有发生滞后一样。

不过,动画周期也可能与帧速率不同步,导致动画周期看起来不规律。例如,假设帧每 0.05 秒更新一次,动画切换图像每 0.075 秒更新一次,则周期将是:

  1. 第 1 帧;0.00 秒;图像 1

  2. 第 2 帧;0.05 秒;图像 1

  3. 第 3 帧;0.10 秒;图像 2

  4. 第 4 帧;0.15 秒;图像 1

  5. 第 5 帧;0.20 秒;图像 1

  6. 第 6 帧;0.25 秒;图像 2

等等...

如果您的计算机可以始终如一地处理帧速率,那么依赖帧的渲染current_frame看起来会更流畅。如果出现延迟,它会暂停在当前状态,并在延迟停止时重新启动,这会使延迟更加明显。这种替代方案稍微容易实现一些,因为您只需要在每次调用时增加 1,而不是处理增量时间 ( dt) 并将其传递给每个对象。

精灵

在此处输入图片描述 在此处输入图片描述 在此处输入图片描述 在此处输入图片描述 在此处输入图片描述 在此处输入图片描述

结果

在此处输入图片描述

解决方案 2:

您可以尝试修改精灵,以便将其图像替换为内部的其他图像update。这样,当渲染精灵时,它看起来就会动起来。

编辑

以下是我写的一个简单的例子:

import pygame
import sys

def load_image(name):
    image = pygame.image.load(name)
    return image

class TestSprite(pygame.sprite.Sprite):
    def __init__(self):
        super(TestSprite, self).__init__()
        self.images = []
        self.images.append(load_image('image1.png'))
        self.images.append(load_image('image2.png'))
        # assuming both images are 64x64 pixels

        self.index = 0
        self.image = self.images[self.index]
        self.rect = pygame.Rect(5, 5, 64, 64)

    def update(self):
        '''This method iterates through the elements inside self.images and 
        displays the next one each tick. For a slower animation, you may want to 
        consider using a timer of some sort so it updates slower.'''
        self.index += 1
        if self.index >= len(self.images):
            self.index = 0
        self.image = self.images[self.index]

def main():
    pygame.init()
    screen = pygame.display.set_mode((250, 250))

    my_sprite = TestSprite()
    my_group = pygame.sprite.Group(my_sprite)

    while True:
        event = pygame.event.poll()
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit(0)

        # Calling the 'my_group.update' function calls the 'update' function of all 
        # its member sprites. Calling the 'my_group.draw' function uses the 'image'
        # and 'rect' attributes of its member sprites to draw the sprite.
        my_group.update()
        my_group.draw(screen)
        pygame.display.flip()

if __name__ == '__main__':
    main()

它假设您有两个图像被调用image1.png,并且image2.png代码位于同一个文件夹中。

解决方案 3:

您应该将所有精灵动画放在一个大“画布”上,因此对于 3 个 20x20 爆炸精灵帧,您将获得 60x20 图像。现在您可以通过加载图像的一个区域来获得正确的帧。

在你的精灵类中,最有可能在更新方法中你应该有类似这样的内容(为了简单起见进行硬编码,我更喜欢有单独的类来负责选择正确的动画帧)。self.f = 0开启__init__

def update(self):
    images = [[0, 0], [20, 0], [40, 0]]
    self.f += 1 if self.f < len(images) else 0
    self.image = your_function_to_get_image_by_coordinates(images[i])

解决方案 4:

对于动画Sprite,必须生成图像(对象)列表pygame.Surface。列表的不同图片显示在每一帧中,就像电影中的图片一样。这给出了动画对象的外观。

获取图像列表的一种方法是加载动画GIF(图形交换格式)。不幸的是,PyGame 没有提供加载动画 GIF 帧的功能。但是,有几种 Stack Overflow 答案可以解决这个问题:

  • 如何在 PyGame 中加载动画 GIF 并获取所有单独的帧?

  • 如何在 pygame 中将精灵制作成 gif 格式?

  • Pygame 和 Numpy 动画

一种方法是使用流行的Pillow库 ( pip install Pillow )。以下函数加载动画GIF的帧并生成对象列表pygame.Surface

from PIL import Image, ImageSequence
def loadGIF(filename):
    pilImage = Image.open(filename)
    frames = []
    for frame in ImageSequence.Iterator(pilImage):
        frame = frame.convert('RGBA')
        pygameImage = pygame.image.fromstring(
            frame.tobytes(), frame.size, frame.mode).convert_alpha()
        frames.append(pygameImage)
    return frames

创建一个pygame.sprite.Sprite维护图像列表的类。实现一个更新方法,在每一帧中选择不同的图像。

将图像列表传递给类构造函数。添加一个index属性,指示当前图像在列表中的索引。在方法中增加索引Update。如果索引大于或等于图像列表的长度,则重置索引(或使用模数(%)运算符)。通过订阅从列表中获取当前图像:

class AnimatedSpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, bottom, images):
        pygame.sprite.Sprite.__init__(self)
        self.images = images
        self.image = self.images[0]
        self.rect = self.image.get_rect(midbottom = (x, bottom))
        self.image_index = 0
    def update(self):
        self.image_index += 1
        if self.image_index >= len(self.images):
            self.image_index = 0
        self.image = self.images[self.image_index]

另请参阅加载动画 GIF和Sprite

示例 GIF(来自动画 Gif、动画图像):

IT科技

最小示例:![IT科技](https://i.sstatic.net/5jD0C.png) repl.it/@Rabbid76/PyGame-SpriteAnimation

IT科技

import pygame
from PIL import Image, ImageSequence

def loadGIF(filename):
    pilImage = Image.open(filename)
    frames = []
    for frame in ImageSequence.Iterator(pilImage):
        frame = frame.convert('RGBA')
        pygameImage = pygame.image.fromstring(
            frame.tobytes(), frame.size, frame.mode).convert_alpha()
        frames.append(pygameImage)
    return frames
 
class AnimatedSpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, bottom, images):
        pygame.sprite.Sprite.__init__(self)
        self.images = images
        self.image = self.images[0]
        self.rect = self.image.get_rect(midbottom = (x, bottom))
        self.image_index = 0
    def update(self):
        self.image_index += 1
        self.image = self.images[self.image_index % len(self.images)]
        self.rect.x -= 5
        if self.rect.right < 0:
            self.rect.left = pygame.display.get_surface().get_width()

pygame.init()
window = pygame.display.set_mode((300, 200))
clock = pygame.time.Clock()
ground = window.get_height() * 3 // 4

gifFrameList = loadGIF('stone_age.gif')
animated_sprite = AnimatedSpriteObject(window.get_width() // 2, ground, gifFrameList)    
all_sprites = pygame.sprite.Group(animated_sprite)

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

    all_sprites.update()

    window.fill((127, 192, 255), (0, 0, window.get_width(), ground))
    window.fill((255, 127, 64), (0, ground, window.get_width(), window.get_height() - ground))
    all_sprites.draw(window)
    pygame.display.flip()

pygame.quit()
exit()
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用