在本教程中,我们将学习如何操纵精灵。精灵是2D图像/动画,我们将使用它们来显示带有alpha通道的图像。精灵总是对着镜头。
现在,精灵经常被用来显示动画人物,粒子,和模拟三维复杂的物体,如树木。
如果你想使用sprite,你需要创建一个“sprite manager”,通过将一个sprite的多个实例集中在一个地方来优化GPU资源。这个管理器是强制性的,即使您想创建一个精灵。你只需要写:
// Create a sprite manager
var spriteManagerTrees = new BABYLON.SpriteManager("treesManager", "Assets/Palm-arecaceae.png", 2000, 800, scene);
创建sprite manager时,您必须决定几个参数:
- Name: a name for this manager.
- The 2D image URL (most of the time, you will want use an image format which contain alpha channel, like .PNG).
- The capacity of this manager : the maximum number of instances in this manager (in our example, we could create 2000 instances of trees).
- The cell size, corresponding to the size of your image, like we’ll see below. Please note that cellSize could be a number or an object made of a width and height properties (Later on you will be able to also specify
spriteManager.cellWidth
andspriteManager.cellHeight
) - The actual scene, to which we will add this manager.
var spriteManagerPlayer = new BABYLON.SpriteManager("playerManager","Assets/Player.png", 2, {width: 64, height: 64}, scene);
这次,我们只需要2个实例,我们定义精灵的大小是64x64
精灵的每张图像都必须包含在一个64像素的正方形中,不能多也不能少。
创建一个实例
现在我们有了管理器,我们可以创建链接到这个管理器的精灵实例。创建一个实例非常简单:
var player = new BABYLON.Sprite("player", spriteManagerPlayer);
如果你想给这个实例添加参数,你可以像操作其他网格一样操作它:
player.position.y = -0.3;
但因为它是一个精灵,你可以使用特定的参数:你可以改变他们的大小,或者他们的方向:
player.size = 0.3;
player.angle = Math.PI/4;
player.invertU = -1;
从Babylon.js v2.1开始,你可以定义精灵的宽度和高度:
player.width = 0.3;
player.height = 0.4;
也可以利用 player.size
在这种情况下,大小,宽度和高度是一样的。
精灵动画
精灵的优势之一是动画。您只需要加载一个大的图像文件,其中将包含所有动画图像,一个挨着另一个。只要注意尊重您在管理器中指定的正方形像素大小(例如64像素)。
下面是一张完整的精灵图片:
这将使我们的球员在超过40个位置,取决于情况(步行,跳跃,…)babylonjs的引擎会自动读取不止一行精灵,所以引擎会为你工作
如果你想开始动画,只需调用这个函数:
player.playAnimation(0, 43, true, 100);
通过调用带有这些参数的«playAnimation»,我们的播放器将从第0帧动画到第43帧。第三个参数表示这个动画是否会循环。最后一个参数是帧之间的延迟(越小,动画越快)。
最后,如果你想进入一个特定的图像(例如最后一个,当字符没有移动时),只需调用:
player.cellIndex = 44;
参考资料: https://doc.babylonjs.com/babylon101/sprites