# 雪碧图

现在您知道了如何从单个图像文件创建精灵。但是,作为一名游戏设计师,你通常会使用雪碧图来制作精灵。Pixi有一些方便的内置方法来帮助您实现这一点。雪碧图是包含子图像的单个图像文件。这些子图像代表了你想在游戏中使用的所有图形。下面是一个包含游戏角色和游戏对象作为子图像的雪碧图示例。

;

整个雪碧图是192 * 192像素。每个图像在自己的32×32像素网格单元。在一个雪碧图上存储和访问所有的游戏图形是一种非常高效的处理和存储图形的方式,Pixi对此进行了优化。

提示

请把这张图保存到你的imgages文件夹下,并命名未tileset.png,后面会用到。

# 使用雪碧图

您可以通过定义与要提取的子图像大小和位置相同的矩形区域来从雪碧图捕获子图像。这是一个火箭子图像的例子,它是从雪碧图中提取出来的。

;

让我们来看看执行此操作的代码。首先,使用Pixi的loader加载器加载tileset.png图像,就像您在前面的示例中所做的那样:

loader
  .add("images/tileset.png")
  .load(setup);
1
2
3

接下来,当图像加载后,使用雪碧图的一个矩形区域内容来创建精灵的图像。下面是提取子图像、创建火箭精灵、定位并显示在画布上的代码。

function setup() {

  //Create the `tileset` sprite from the texture
  let texture = TextureCache["images/tileset.png"];

  //Create a rectangle object that defines the position and
  //size of the sub-image you want to extract from the texture
  //(`Rectangle` is an alias for `PIXI.Rectangle`)
  let rectangle = new Rectangle(96, 64, 32, 32);

  //Tell the texture to use that rectangular section
  texture.frame = rectangle;

  //Create the sprite from the texture
  let rocket = new Sprite(texture);

  //Position the rocket sprite on the canvas
  rocket.x = 32;
  rocket.y = 32;

  //Add the rocket to the stage
  app.stage.addChild(rocket);
  
  //Render the stage   
  app.renderer.render(app.stage);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

Pixi有一个内置的Rectangle对象(Pixi.Rectangle),它是用于定义矩形形状的通用对象。它有四个参数。前两个参数定义了矩形的xy位置。后两个定义了它的宽度width高度height。下面是定义Rectangle对象的格式。

let rectangle = new PIXI.Rectangle(x, y, width, height);
1

rectangle矩形对象只是一个数据对象;你可以决定如何使用它。在我们的示例中,我们使用它来定义要提取的雪碧图上的子图像的位置和区域。Pixi纹理有一个有用的属性叫做frame,可以设置为任何Rectangle对象。frame将纹理裁剪为矩形的尺寸。下面代码就是使用frame裁剪纹理的大小和位置的火箭。

let rectangle = new Rectangle(192, 128, 64, 64);
texture.frame = rectangle;
1
2

然后你可以使用裁剪后的纹理来创建精灵。

let rocket = new Sprite(texture);
1

由于您需要频繁地使用雪碧图制作精灵纹理,因此Pixi提供了一种更方便的方法来帮助您完成这项工作——让我们看看下一步要做什么。

lastUpdate: 2/3/2023, 2:34:54 AM