实例学习: 宝物猎人

宝藏猎人。(你能在examples文件夹中找到它。) 宝藏猎手是一个简单的完整的游戏的例子,它能让你把目前所学的所有工具都用上。用键盘的方向键可以帮助探险者找到宝藏并带它出去。六只怪物在地牢的地板上上下移动,如果它们碰到了探险者,探险者变为半透明,而且他右上角的血条会减少。如果所有的血都用完了,”You Lost!”会出现在舞台上;如果探险者带着宝藏到达了出口,显示 “You Won!” 。尽管它是一个基础的原型,宝藏猎手包含了很多大型游戏里很大一部分元素:纹理贴图集,人机交互,碰撞以及多个游戏场景。让我们一起去看看游戏是如何被它们组合起来的,以便于你可以用它作你自己开发的游戏的起点。

代码结构

treasureHunter.html 文件,你将会看到所有的代码都在一个大的文件里。下面是一个关于如何组织所有代码的概览:

  1. //Setup Pixi and load the texture atlas files - call the `setup`//function when they've loadedfunction setup() { //Initialize the game sprites, set the game `state` to `play` //and start the 'gameLoop'}function gameLoop(delta) { //Runs the current game `state` in a loop and renders the sprites}function play(delta) { //All the game logic goes here}function end() { //All the code that should run at the end of the game}//The game's helper functions://`keyboard`, `hitTestRectangle`, `contain` and `randomInt`

把这个当作你游戏代码的蓝图,让我们看看每一部分是如何工作的。

用 setup 函数初始化游戏

setup函数就会执行。它只会执行一次,可以让你为游戏执行一次安装任务。这是一个用来创建和初始化对象、精灵、游戏场景、填充数据数组或解析加载JSON游戏数据的好地方。 setup函数的缩略图和它要执行的任务。

  1. function setup() { //Create the `gameScene` group //Create the `door` sprite //Create the `player` sprite //Create the `treasure` sprite //Make the enemies //Create the health bar //Add some text for the game over message //Create a `gameOverScene` group //Assign the player's keyboard controllers //set the game state to `play` state = play; //Start the game loop app.ticker.add(delta => gameLoop(delta));}

state = play;和gameLoop()可能是最重要的。运行 gameLoop 切换了游戏的引擎,而且引发了 play 一直被循环调用。但是在我们看它如何工作之前,让我们看看 setup 函数里的代码都做了什么。

创建游戏场景

setup 函数创建了两个被称为gameScene 和 gameOverScene的 Container 分组。他们都被添加到了舞台上。

  1. gameScene = new Container();app.stage.addChild(gameScene);gameOverScene = new Container();app.stage.addChild(gameOverScene);

gameScene分组。游戏结束的文字在游戏结束后显示,应当被添加到gameOverScene分组。 setup 函数中添加的,但是 gameOverScene不应在游戏一开始的时候显示,所以它的 visible 属性被初始化为 false。

  1. gameOverScene.visible = false;

gameOverScene 的 visible 属性会被设置为 true 。

制作地牢,门,猎人和宝藏

gameScene 的孩子添加进来的。

  1. //Create an alias for the texture atlas frame idsid = resources["images/treasureHunter.json"].textures;//Dungeondungeon = new Sprite(id["dungeon.png"]);gameScene.addChild(dungeon);//Doordoor = new Sprite(id["door.png"]);door.position.set(32, 0);gameScene.addChild(door);//Explorerexplorer = new Sprite(id["explorer.png"]);explorer.x = 68;explorer.y = gameScene.height / 2 - explorer.height / 2;explorer.vx = 0;explorer.vy = 0;gameScene.addChild(explorer);//Treasuretreasure = new Sprite(id["treasure.png"]);treasure.x = gameScene.width - treasure.width - 48;treasure.y = gameScene.height / 2 - treasure.height / 2;gameScene.addChild(treasure);

gameScene 分组会使我们在游戏结束的时候去隐藏 gameScene 和显示 gameOverScene 操作起来更简单。

制造泡泡怪们

1 或者 -1 ,这就是每个怪物和相邻的下一个怪物运动的方向都是相反的原因,每个被创建的怪物都被放进了一个名为 blobs 的数组。

  1. let numberOfBlobs = 6, spacing = 48, xOffset = 150, speed = 2, direction = 1;//An array to store all the blob monstersblobs = [];//Make as many blobs as there are `numberOfBlobs`for (let i = 0; i < numberOfBlobs; i++) { //Make a blob let blob = new Sprite(id["blob.png"]); //Space each blob horizontally according to the `spacing` value. //`xOffset` determines the point from the left of the screen //at which the first blob should be added let x = spacing * i + xOffset; //Give the blob a random `y` position let y = randomInt(0, stage.height - blob.height); //Set the blob's position blob.x = x; blob.y = y; //Set the blob's vertical velocity. `direction` will be either `1` or //`-1`. `1` means the enemy will move down and `-1` means the blob will //move up. Multiplying `direction` by `speed` determines the blob's //vertical direction blob.vy = speed * direction; //Reverse the direction for the next blob direction *= -1; //Push the blob into the `blobs` array blobs.push(blob); //Add the blob to the `gameScene` gameScene.addChild(blob);}

制作血条

healthBar 分组。 healthBar 然后被添加到 gameScene 并在舞台上被定位。

  1. //Create the health barhealthBar = new PIXI.DisplayObjectContainer();healthBar.position.set(stage.width - 170, 4)gameScene.addChild(healthBar);//Create the black background rectanglelet innerBar = new PIXI.Graphics();innerBar.beginFill(0x000000);innerBar.drawRect(0, 0, 128, 8);innerBar.endFill();healthBar.addChild(innerBar);//Create the front red rectanglelet outerBar = new PIXI.Graphics();outerBar.beginFill(0xFF3300);outerBar.drawRect(0, 0, 128, 8);outerBar.endFill();healthBar.addChild(outerBar);healthBar.outer = outerBar;

healthBar 添加了一个名为 outer 的属性。它仅仅是引用了 outerBar (红色的矩形)以便于过会儿能够被很方便的获取。

  1. healthBar.outer = outerBar;

outerBar 的宽度,你可以像这样顺畅的写如下代码:

  1. healthBar.outer.width = 30;

这样的代码相当整齐而且可读性强,所以我们会一直保留它!

制作消息文字

gameOverScene。因为 gameOverScene 的 visible 属性设为了 false ,当游戏开始的时候,你看不到这些文字。这段代码来自 setup 函数,它创建了消息文字,而且被添加到了 gameOverScene。

  1. let style = new TextStyle({ fontFamily: "Futura", fontSize: 64, fill: "white" });message = new Text("The End!", style);message.x = 120;message.y = app.stage.height / 2 - 32;gameOverScene.addChild(message);

开始游戏

play 函数里,这是一个被循环执行的函数。这里是 play 函数都做了什么的总体概览:

  1. function play(delta) { //Move the explorer and contain it inside the dungeon //Move the blob monsters //Check for a collision between the blobs and the explorer //Check for a collision between the explorer and the treasure //Check for a collision between the treasure and the door //Decide whether the game has been won or lost //Change the game `state` to `end` when the game is finsihed}

让我们弄清楚这些特性都是怎么工作的吧。

移动探险者

play 函数里, keyboard 对象修改探险者的速度,这个速度和探险者的位置相加。

  1. explorer.x += explorer.vx;explorer.y += explorer.vy;

控制运动的范围

一个新的地方的是,探险者的运动是被包裹在地牢的墙体之内的。绿色的轮廓表明了探险者运动的边界。 contain 的自定义函数可以帮助实现。

  1. contain(explorer, {x: 28, y: 10, width: 488, height: 480});

contain 接收两个参数。第一个是你想控制的精灵。第二个是包含了 x, y, width 和height属性的任何一个对象。在这个例子中,控制对象定义了一个区域,它稍微比舞台小了一点,和地牢的尺寸一样。 contain 函数。函数检查了精灵是否跨越了控制对象的边界。如果超出,代码会把精灵继续放在那个边界上。 contain 函数也返回了一个值可能为”top”, “right”, “bottom” 或者 “left” 的 collision 变量,取决于精灵碰到了哪一个边界。(如果精灵没有碰到任何边界,collision 将返回 undefined 。)

  1. function contain(sprite, container) { let collision = undefined; //Left if (sprite.x < container.x) { sprite.x = container.x; collision = "left"; } //Top if (sprite.y < container.y) { sprite.y = container.y; collision = "top"; } //Right if (sprite.x + sprite.width > container.width) { sprite.x = container.width - sprite.width; collision = "right"; } //Bottom if (sprite.y + sprite.height > container.height) { sprite.y = container.height - sprite.height; collision = "bottom"; } //Return the `collision` value return collision;}

collision 的返回值在代码里是如何让怪物在地牢的顶部和底部之间来回反弹的。

移动怪物

play 函数也能够移动怪物,保持它们在地牢的墙体之内,并检测每个怪物是否和玩家发生了碰撞。如果一只怪物撞到了地牢的顶部或者底部的墙,它就会被设置为反向运动。完成所有这些功能都是通过一个 forEach循环,它每一帧都会遍历在 blobs 数组里的每一个怪物。

  1. blobs.forEach(function(blob) { //Move the blob blob.y += blob.vy; //Check the blob's screen boundaries let blobHitsWall = contain(blob, {x: 28, y: 10, width: 488, height: 480}); //If the blob hits the top or bottom of the stage, reverse //its direction if (blobHitsWall === "top" || blobHitsWall === "bottom") { blob.vy *= -1; } //Test for a collision. If any of the enemies are touching //the explorer, set `explorerHit` to `true` if(hitTestRectangle(explorer, blob)) { explorerHit = true; }});

contain 函数的返回值是如何被用来让怪物在墙体之间来回反弹的。一个名为 blobHitsWall 的变量被用来捕获返回值:

  1. let blobHitsWall = contain(blob, {x: 28, y: 10, width: 488, height: 480});

blobHitsWall 通常应该是 undefined。但是如果怪物碰到了顶部的墙,blobHitsWall 将会变成 “top”。如果碰到了底部的墙,blobHitsWall 会变为 “bottom”。如果它们其中任何一种情况为 true,你就可以通过给怪物的速度取反来让它反向运动。这是实现它的代码:

  1. if (blobHitsWall === "top" || blobHitsWall === "bottom") { blob.vy *= -1;}

vy (垂直速度)乘以 -1 就会反转它的运动方向。

检测碰撞

hitTestRectangle 来指明是否有敌人碰到了猎人。

  1. if(hitTestRectangle(explorer, blob)) { explorerHit = true;}

hitTestRectangle 返回 true,意味着发生了一次碰撞,名为 explorerHit 的变量被设置为了 true。如果 explorerHit为 true, play 函数让猎人变为半透明,然后把 health 条减少1像素的宽度。

  1. if(explorerHit) { //Make the explorer semi-transparent explorer.alpha = 0.5; //Reduce the width of the health bar's inner rectangle by 1 pixel healthBar.outer.width -= 1;} else { //Make the explorer fully opaque (non-transparent) if it hasn't been hit explorer.alpha = 1;}

explorerHit 是 false,猎人的 alpha 属性将保持1,完全不透明。 play 函数也要检测宝箱和探险者之间的碰撞。如果发生了一次撞击, treasure 会被设置为探险者的位置,在做一点偏移。看起来像是猎人携带着宝藏一样。 这段代码实现了上述效果:

  1. if (hitTestRectangle(explorer, treasure)) { treasure.x = explorer.x + 8; treasure.y = explorer.y + 8;}

处理到达出口和结束游戏

游戏结束有两种方式:如果你携带宝藏到达出口你将赢得游戏,或者你的血用完你就死了。 state 会被设置为 end, message 文字会显示 “You won!”。

  1. if (hitTestRectangle(treasure, door)) { state = end; message.text = "You won!";}

state 也会被设置为 end, message 文字会显示 “You Lost!”。

  1. if (healthBar.outer.width < 0) { state = end; message.text = "You lost!";}

但是这是什么意思呢?

  1. state = end;

gameLoop 在持续的每秒60次的更新 state 函数。 gameLoop 的代码如下:

  1. function gameLoop(delta){ //Update the current game state: state(delta);}

state 设定的初始值为 play,这也就是为什么 play 函数会循环执行。通过设置 state 为 end 我们告诉代码我们想循环执行另一个名为 end 的函数。在大一点的游戏你可能会为每一个游戏等级设置 tileScene 状态和状态集,像leveOne, levelTwo 和 levelThree。 end 函数是什么?就是它!

  1. function end() { gameScene.visible = false; gameOverScene.visible = true;}

gameScene 和显示 gameOverScene 。 这是一个如何更换游戏状态的一个很简单的例子,但是你可以想在你的游戏里添加多少状态就添加多少状态,然后给它们添加你需要的代码。然后改变 state 为任何你想循环的函数。 这就是完成宝藏猎人所需要的一切了。然后再通过更多一点的工作就能把这个简单的原型变成一个完整的游戏 - 快去试试吧!