HTML5游戏开发(四):飞机大战之显示场景和元素

2,793 阅读3分钟

《HTML5游戏开发》系列文章的目的有:一、以最小的成本去入门egret小项目开发,官方的教程一直都是面向中重型;二、egret可以非常轻量;三、egret相比PIXI.js和spritejs文档更成熟、友好;四、学习从0打造高效的开发工作流。

接下来的几篇文章里,我们将会创建一个完整的飞机大战的游戏。 本文我们将会:

  • 使用工具函数loadImage来快速实现图片载入。
  • 显示游戏的背景、友机和敌机。

游戏完整源码:github.com/wildfirecod…

在线展示:wildfirecode.com/egret-plane…

配置游戏区域

index.html<div>上增加属性data-content-widthdata-content-height来设置游戏区域的大小尺寸。

 <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函数。

//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;

也可以使用它来并行加载多张图片,它将按顺序返回每个位图。在本例中,我们会用它来并行加载游戏背景、友机和敌机三张图片。随后将它们按顺序直接添加到游戏场景当中

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;
    ...
}

运行结果