制作简单游戏:第六部分
完整项目见此处。请先阅读第一部分、第二部分、第三部分、第四部分和第五部分。
用户界面
界面是玩家首先看到的内容,却常常是制作游戏时最后才考虑的部分。好的界面不仅赋予游戏鲜明风格,还会直接影响有多少人能够顺利游玩。
PlayCanvas 使用 Screen 组件和 Element 组件构建界面,更多细节见用户手册。
界面实体

界面按 Menu、In Game 和 Game Over 三种游戏状态划分,每个状态对应一个 Screen 实体,进入状态时激活。我们还为叠加层单独设置 Screen。菜单中的叠加层显示在足球后方,因此使用三维 Screen 组件,在世界空间中将其渲染到球后。
图像与文字

通过 Element 组件向界面添加图像和文字。该组件可使用纹理资源显示图像,或使用字体资源显示文字。

界面脚本
下面查看主菜单脚本。
- ESM
- 传统脚本
import { Script } from 'playcanvas';
export class UiMenu extends Script {
static scriptName = "uiMenu";
/**
* @attribute
* @title Overlay
* @type {Entity}
*/
overlay = null;
// initialize code called once per entity
initialize() {
this.on('enable', this.onEnable, this);
this.on('disable', this.onDisable, this);
this.onEnable();
}
onEnable() {
// Listen for clicks on the background
this.overlay.enabled = true;
this.overlay.element.on("click", this.start, this);
if (this.ball) {
this.ball.model.meshInstances[0].material.depthTest = false;
}
}
onDisable() {
this.overlay.enabled = false;
// Stop listening to events
this.overlay.element.off("click", this.start, this);
}
start(e) {
this.app.fire("ui:start");
// prevent touch and mouse events
e.stopPropagation();
}
}
var UiMenu = pc.createScript('uiMenu');
UiMenu.attributes.add("overlay", {type: "entity"});
// initialize code called once per entity
UiMenu.prototype.initialize = function() {
this.on('enable', this.onEnable, this);
this.on('disable', this.onDisable, this);
this.onEnable();
};
UiMenu.prototype.onEnable = function () {
// Listen for clicks on the background
this.overlay.enabled = true;
this.overlay.element.on("click", this.start, this);
if (this.ball) {
this.ball.model.meshInstances[0].material.depthTest = false;
}
};
UiMenu.prototype.onDisable = function () {
this.overlay.enabled = false;
// Stop listening to events
this.overlay.element.off("click", this.start, this);
};
UiMenu.prototype.start = function (e) {
this.app.fire("ui:start");
// prevent touch and mouse events
e.stopPropagation();
};
首先定义属性引用叠加层元素。这个全屏元素会将屏幕染为绿色,同时用于检测输入,因为我们只关心用户是否点击了屏幕。
实体启用时,启用全屏叠加层并开始监听点击事件;实体禁用时,停止监听并隐藏叠加层。点击发生后触发主游戏脚本监听的 ui:start 事件,进而切换游戏状态。
其他两个界面脚本也采用类似方式,监听游戏事件并触发界面事件。
游戏完成
本系列到此结束!希望你已学会如何使用 PlayCanvas 组织和构建游戏。如对教程有反馈,请在论坛联系我们。