《HTML5游戏开发》系列文章的目的有:1、以最小的成本去入门egret小项目开发,官方的教程一直都是面向中重型;2、egret能够很是轻量;3、egret相比PIXI.js和spritejs文档更成熟、友好;4、学习从0打造高效的开发工做流。html
接下来的几篇文章里,咱们将会建立一个完整的飞机大战的游戏。 本文咱们将会:webpack
游戏完整源码:github.com/wildfirecod…git
在线展现:wildfirecode.com/egret-plane…github
在index.html
的<div>
上增长属性data-content-width
和data-content-height
来设置游戏区域的大小尺寸。web
<div style="margin: auto;width: 100%;height: 100%;" class="egret-player" data-entry-class="Main" data-scale-mode="fixedWidth" data-content-width="720" data-content-height="1200">
</div>
复制代码
如今游戏的宽高为720x1200
。函数
将背景(background.png)、友机(hero.png)、敌机(enemy.png)图片添加到assets
目录。工具
为了下降引擎的复杂度以及初学者的成本,咱们把加载图片的逻辑作了封装,这就是loadImage函数。post
//loadImage方法API
const loadImage: (url: string | string[]) => Promise<egret.Bitmap> | Promise<egret.Bitmap[]>
复制代码
你能够用它来加载单独的一张图片,此时函数会返回单个位图
。在egret中,位图对应的类是egret.Bitmap
,它是一个显示对象
,能够直接填充到显示容器
Main
中。学习
const image = await loadImage('assets/background.png') as egret.Bitmap;
复制代码
也能够使用它来并行加载多张图片,它将按顺序返回每一个位图
。在本例中,咱们会用它来并行加载游戏背景、友机和敌机三张图片。随后将它们按顺序直接添加到游戏场景当中ui
import { loadImage } from "./assetUtil";
const assets = ['assets/background.png', 'assets/hero.png', 'assets/enemy.png'];
const images = await loadImage(assets) as egret.Bitmap[];
const [bg, hero, enemy] = images;//按顺序返回背景、友机、敌机的位图
//将背景添加到游戏场景的最底层
this.addChild(bg);
//将飞机添加到游戏背景之上
this.addChild(hero);
this.addChild(enemy);
复制代码
下图示意了图片的并行加载。
为了方便定位图片,咱们将飞机的锚点同时在垂直和水平方向居中。
createGame() {
...
//设置飞机的锚点为飞机中心点
this.centerAnchor(hero);
this.centerAnchor(enemy);
...
}
centerAnchor(displayObject: egret.DisplayObject) {
displayObject.anchorOffsetX = displayObject.width / 2;
displayObject.anchorOffsetY = displayObject.height / 2;
}
复制代码
咱们将敌机在水平方向上居中,垂直方向上将其放置在距离顶部200像素的地方。
createGame() {
...
enemy.x = this.stage.stageWidth / 2;
enemy.y = 200;
...
}
复制代码
咱们将友机在水平方向上居中,垂直方向上将其放置在距离底部100像素的地方。
createGame() {
...
hero.x = this.stage.stageWidth / 2;
hero.y = this.stage.stageHeight - 100;
...
}
复制代码