如何最有效地更改用于显示对象的精灵?

2024-06-02 06:11:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个物体可以根据它所面对的方向改变它的显示。该对象采用4x4帧网格,并将每行4帧用作每个状态的动画。在

目前,我正在使用以下方法将这些加载到单独的精灵中:

def create_animation(image_grid, start_idx, end_idx):
    frames = []
    for frame in image_grid[start_idx:end_idx]:
        frames.append(pyglet.image.AnimationFrame(frame, 0.1))
    return pyglet.sprite.Sprite(pyglet.image.Animation(frames))

然后将应该显示的精灵添加到要绘制的batch中,并在不应该绘制时删除它。在

然而,在阅读文档时,我看到了:

Sprite.batch

The sprite can be migrated from one batch to another, or removed from its batch (for individual drawing). Note that this can be an expensive operation.

有没有更好的方法来实现我所要做的,而不必在批量中切换单个精灵的性能呢?在


Tags: 方法imageforframesbatch绘制framestart
1条回答
网友
1楼 · 发布于 2024-06-02 06:11:27

可以将图像加载为TextureGrid:

    img = pyglet.resource.image("obj_grid.png")
    img_grid = pyglet.image.ImageGrid(   
        img,
        4,  # rows, direction
        4  # cols, frames of the animation
    )
    texture_grid = pyglet.image.TextureGrid(img_grid)  # this is the one you actually use

创建(单个)精灵:

^{pr2}$

确定/改变方向(“行”,我是根据输入猜测的?)。在

循环0-3(“col”/动画帧):

    pyglet.clock.schedule_interval(change_frame, 0.1, my_object)

    def change_frame(dt, my_object):  # pyglet always passes 'dt' as argument on scheduled calls
        my_object.col += 1
        my_object.col = my_object.col & 3 #  or my_object.col % 3 if its not a power of 2

并手动设置框架:

    current_frame = self.texture_grid[self.row, self.col].get_texture()
    my_object._set_texture(current_frame)

不需要对draw()进行其他调用,也不必搅乱batch()。一切照常绘制,但您可以根据需要更改它绘制的纹理:)

相关问题 更多 >