移动精灵
ticker。这被称为 游戏循环 。任何在游戏循环里的代码都会1秒更新60次。你可以用下面的代码让 cat 精灵以每帧1像素的速率移动。
function setup() { //Start the game loop by adding the `gameLoop` function to //Pixi's `ticker` and providing it with a `delta` argument. app.ticker.add(delta => gameLoop(delta));}function gameLoop(delta){ //Move the cat 1 pixel cat.x += 1;}
如果你运行了上面的代码,你会看到精灵逐步地移动到舞台的一边。
游戏循环 的时候,都会为这只猫增加1像素的x轴位移。
cat.x += 1;
ticker的函数都会每秒被执行60次。你可以看见函数里面提供了一个delta的内容,他是什么呢?
delta的值代表帧的部分的延迟。你可以把它添加到cat的位置,让cat的速度和帧率无关。下面是代码:
cat.x += 1 + delta;
delta的值其实是一种审美的选择。它往往只在你的动画没法跟上60帧的速率时候出现(比如你的游戏运行在很老旧的机器上)。教程里面不会用到delta变量,但是如果你想用就尽情的用吧。
requestAnimationFrame像这样创建:
function gameLoop() { //Call this `gameLoop` function on the next screen refresh //(which happens 60 times per second) requestAnimationFrame(gameLoop); //Move the cat cat.x += 1;}//Start the loopgameLoop();
随你喜欢。 这就是移动的全部。只要在循环中改变精灵的一点点属性,它们就会开始相应的动画。如果你想让它往相反的方向移动,只要给它一个负值,像 -1。 你能在 movingSprites.html 文件中找到这段代码 - 这是全部的代码:
//Aliaseslet Application = PIXI.Application, Container = PIXI.Container, loader = PIXI.loader, resources = PIXI.loader.resources, TextureCache = PIXI.utils.TextureCache, Sprite = PIXI.Sprite, Rectangle = PIXI.Rectangle;//Create a Pixi Applicationlet app = new Application({ width: 256, height: 256, antialias: true, transparent: false, resolution: 1 });//Add the canvas that Pixi automatically created for you to the HTML documentdocument.body.appendChild(app.view);loader .add("images/cat.png") .load(setup);//Define any variables that are used in more than one functionlet cat;function setup() { //Create the `cat` sprite cat = new Sprite(resources["images/cat.png"].texture); cat.y = 96; app.stage.addChild(cat); //Start the game loop app.ticker.add(delta => gameLoop(delta));}function gameLoop(delta){ //Move the cat 1 pixel cat.x += 1; //Optionally use the `delta` value //cat.x += 1 + delta;}
cat 变量需要在setup 和 gameLoop函数之外定义,然后你可以在全局中任何地方都能获取到它们)
你可以让精灵的位置,角度或者大小动起来 - 什么都可以!你会在下面看到更多精灵动画的例子。
