构建窗口
# 构建窗口
阅读本节时,默认你已经阅读了上一届节内容。
# 继承窗口基类,并添加至场景内
第二版推荐继承窗口类Window_Base
,即我们俗称的窗口基类。新建类VariableProgressWindow
并继承Window_Base
。代码如下:
class VariableProgressWindow extends Window_Base {
constructor() {
super();
}
}
2
3
4
5
# 补全完善的构造函数参数
上述的代码写法是无参类型的构造函数写法。事实上,窗口类要求我们在实例化对象时需要增加更多的参数。至少需要x坐标
,y坐标
,窗口宽度
,窗口高度
这四个参数。那么我们的变量进度窗口类应该写成如下代码:
class VariableProgressWindow extends Window_Base {
constructor(x = 0, y = 0, width = 0, height = 0) {
super(x, y, width, height);
}
}
2
3
4
5
窗口基类本身实例化时,其构造函数也是需要上述的4
个参数的,所以这里的写法需要将参数传入给super
函数,让父类的构造函数可以实例化窗口。这里还使用了默认参数值
的语法糖,来保证函数的健壮性。
第二版不会介绍ES6
的具体语法使用细节,内容过多,细节繁琐。请执行查阅相关的资料学习相关的语法。
点此阅读js
的super
关键字相关知识 (opens new window)。
点此阅读默认参数值
的相关知识 (opens new window)。
为了代码的安全起见,第二版建议把initialize
函数也补全。代码如下:
class VariableProgressWindow extends Window_Base {
constructor(x = 0, y = 0, width = 0, height = 0) {
super(x, y, width, height);
this.initialize(x, y, width, height);
}
initialize(x, y, width, height) {
super.initialize(x, y, width, height);
}
}
2
3
4
5
6
7
8
9
# 完善构造函数的写法
补全宽度的自运算。在mv
架构中,有相当一部分的窗口宽度是一开始就定好的,其宽高总是用windowWidth
和windowHeight
函数实现的。既然我们实现了宽高的内部预设,那么构造函数就可以不要求传递宽高值。写法如下:
class VariableProgressWindow extends Window_Base {
constructor(x = 0, y = 0) {
super(x, y);
this.initialize(x, y);
}
windowWidth() {
return 240;
}
windowHeight() {
return 240;
}
initialize(x, y) {
let width = this.windowWidth();
let height = this.windowHeight();
super.initialize(x, y, width, height);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 用ES6的super关键字来替代ES5的call(this)方式来实现构造函数的继承
第二版是推荐各位使用ES6
语法糖。如果是使用传统的ES5
方式来写插件,那么我们的类会写成如下的这种形式:
function VariableProgressWindow() {
this.initialize.apply(this, arguments);
}
VariableProgressWindow.prototype = Object.create(Window_Base.prototype);
VariableProgressWindow.prototype.constructor = Window_Base;
VariableProgressWindow.prototype.initialize = function () {
Window_Base.prototype.initialize.call(this, x, y, width, height);
};
2
3
4
5
6
7
8
如果你经常阅读mv
源码,或者是其他人的插件,你会几乎总是会遇到类似于上述代码的写法。这个写法在js
中被称呼为寄生组合式继承
。这个继承写法是繁琐的,甚至是恶心的,糟粕的。我不希望以后的开发者在现代前端技术突飞猛进的时代内,仍旧使用自2015年以来就该被废弃的js
代码写法。
# 将窗口添加到VariableProgressScene场景内
场景类有多个生命周期函数,我推荐你在create
生命周期内将窗口添加到场景类,代码如下。在场景类VariableProgressScene
的create
函数内增加如下的代码:
create() {
super.create();
const halfGraphicsX = Graphics.width / 2;
const halfGraphicsY = Graphics.height / 2;
let _variableProgressWindow = new VariableProgressWindow(
halfGraphicsX,
halfGraphicsY
);
this.addWindow(_variableProgressWindow);
}
2
3
4
5
6
7
8
9
10
让窗口的x
,y
坐标位置为可见宽高
的一半。但要注意,这并不意味着窗口居中对齐。