精灵

精灵序列是包含多个游戏图像的图片文件。

这个例子我们使用公网文件 Glitch assets collection。感谢 Tiny Speck 开放他们的资源! 这里我们将要用到这些图片:

在这种情况下,它描述了单个动画的多个帧,但精灵序列结合许多不同的动画是很常见的。

加载精灵序列

我们使用精灵序列之前不仅要加载他们, 而且要指定每一个精灵的位置。你可以使用 Crafty.load 完成这一步。

var assetsObj = {
    "sprites": {
        // This spritesheet has 16 images, in a 2 by 8 grid
        // The dimensions are 832x228
        "glitch_walker.png": {
            // This is the width of each image in pixels
            tile: 104,
            // The height of each image
            tileh: 114,
            // We give names to three individual images
            map: {
                walker_start: [0, 0],
                walker_middle: [7, 0],
                walker_end: [7, 1]
            }
        }
    }
};

Crafty.load(assetsObj, callback)

有些精灵序列在每个精灵或整个图片周围有空白。你可以使用 paddingX, paddingY, 和 paddingAroundBorder 字段来指定。

静态精灵

要使用静态精灵,我们参考前面定义的映射。Crafty 将有自动生成的组件与这些名称,添加 "Sprite" 组件到场景。

// This will display the image associated with walker_start
// It automatically gets the dimensions of that image: 104x114
var actual_size = Crafty.e("2D, Canvas, walker_start")
    .attr({x: 10, y:10});

// An image from a different part of the sprite sheet
// Here we scale it to half size
var small_sprite = Crafty.e("2D, Canvas, walker_middle")
    .attr({x:150, y:10, w:52, h:57})

精灵动画

你可以使用 "SpriteAnimation" 组件把上边的精灵做成一个动画。

var walker = Crafty.e('2D, Canvas, walker_start, SpriteAnimation');

动画是通过定义和播放帧序列来实现的。要定义帧动画, 调用 reel 方法并传递一个名字,一个持续时间,和一个帧序列. 在这里我们定义了一个称为 "walking" 的帧动画,它将持续1秒,并按照我们的希望,顺序地显示16个帧:

walker.reel("walking", 1000, [
    [0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0],
    [0, 1], [1, 1], [2, 1], [3, 1], [4, 1], [5, 1], [6, 1], [7, 1]
])

然后,要运行动画,你只需要简单的调用 animate 方法就可以启动它!这个方法需要传递两个参数: 帧序列的名字,和一个播放时间,如果要无限的播放下去,那就传 -1:

walker.animate("walking", -1)

最后,我们把这个完整的例子运行在 jsbin,我们的精灵将在里边行走:

试着在 go() 后边增加 walker.animationSpeed = 2 !