HTML5遊戲開發(四):飛機大戰之顯示場景和元素
《HTML5遊戲開發》系列文章的目的有:一、以最低的成本去入門egret小專案開發,官方的教程一直都是面向中重型;二、egret可以很輕量;三、egret相比PIXI.js和spritejs有他的優勢所在;四、學習從0打造高效的開發工作流。
- ofollow,noindex">HTML5遊戲開發(一):3分鐘建立一個hello world
- HTML5遊戲開發(二):使用TypeScript編寫程式碼
- HTML5遊戲開發(三):使用webpack構建TypeScript應用
- HTML5遊戲開發(四):飛機大戰之顯示場景和元素
接下來的幾篇文章裡,我們將會建立一個完整的飛機大戰的遊戲。 本文我們將會:
- 使用工具函式loadImage來快速實現圖片載入。
- 顯示遊戲的背景、友機和敵機。
遊戲完整原始碼: github.com/wildfirecod…
線上展示: wildfirecode.com/egret-plane…
配置遊戲區域
在 index.html
的 <div>
上增加屬性 data-content-width
和 data-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; ... } 複製程式碼