译:Gamemaker Studio 2.3 语法详解( 四 )


scr_greet("hi!");// 跟以前一样
other .explode;// 这样可以
init_s [i];// 这样也可以
method (other,scr_some);// 对'other'执行'scr_some' , 不用加'with'内置函数引用
可以这样
varf =show_debug_message;
f ("hello!");
而且我们可以自动为内置函数建立索引 。
varfunctions ={};
for(vari =0;i <10000;i++){
varname =_get_name(i);
if(string_char_at(name,1)=="<")break;
functions [$name]=method(undefined,i);
show_debug_message(string(i)+": "+name);
}
// `functions` now contains name->method pairs
这会输出:
0:camera_create
1:camera_create_view
2:camera_destroy
...
2862:layer_sequence_get_speedscale
2863:layer_sequence_get_length
2864:sequence_instance_exists
索引对于调试和脚本工具来说是非常方便的--例如 , GMLive 现在使用这种机制 , 而不是有一个充满脚本的庞大文件来包装每一个已知的内置函数 。
Constructor(构造函数)
Constructor 是一个标有 Constructors 后缀关键字的函数 。
functionVector2(_x,_y)constructor {
x =_x;
y =_y;
}
这使你能够做到
varv =newVector2(4,5);
show_debug_message (v.x);// 4
show_debug_message (v);// { x: 4, y: 5 }
简而言之 ,new 关键字可以自动创建一个空结构 , 为它调用构造函数 , 然后返回它 。 就像其他编程语言中的类一样! 但还有更多 。
Static variables 静态变量
GMS2 将把 constructor 中的静态变量视为存在于由它创建的 struct 实例中 , 只要 struct 实例没有覆盖该变量 。
这类似于变量定义对对象的作用 , 或原型在其他编程语言中的作用(如 Java 原型或 Lua 的元数据) 。
【译:Gamemaker Studio 2.3 语法详解】这可以用于默认值(然后可以覆盖) , 但最重要的是 , 可以向 struct 添加 method, 而不需要在每个 struct 实例中实际存储:
functionVector2(_x,_y)constructor {
x =_x;
y =_y;
staticadd =function(v){
x +=v.x;
y +=v.y;
}
}
// ... 然后
vara =newVector2(1,2);
varb =newVector2(3,4);
a.add(b);
show_debug_message (a);// { x : 4, y : 6 }
注意:如果您想在 constructor 中直接覆盖静态变量(而不是在其中的 function 中) , 您需要使用 self.variable 来区分 static variable 和 new struct 的变量:
functionEntityconstructor {
staticuid =0;
self.uid =uid++;
}
(这将给每个实体一个唯一的 ID )
Inheritance(继承)
一个 constructor 可以使用: Parent 语法从另一个 constructor 继承:
functionElement(_x,_y)constructor {
staticstep =function{};
staticdraw =function(_x,_y){};
x =_x;
y =_y;
}
functionLabel(_x,_y,_text):Element(_x,_y)constructor {
staticdraw =function(_ofs_x,_ofs_y){
draw_text (_ofs_x +x,_ofs_y +y,text);
};
text =_text;
}
这将首先调用父 constructor, 然后再调用子 constructor。
在子 constructor 中定义的静态变量优先于在父 constructor 中定义的静态变量 , 这就为覆盖父字段提供了一种方法--因此 , 用上述方法 , 你可以做到
varlabel =newLabel(100,100,"Hello!");
label .step;// 调用父 step 函数
label .draw(5,5);// 调用子 draw 函数
如果你确实需要父 method 是可调用的 , 你可以在覆写子 method 之前存储它 , 比如说
functionLabel(_x,_y,_text):Element(_x,_y)constructor {
static__step =step;// 现在引用父 constructor 的 step 函数
staticstep =function(_ofs_x,_ofs_y){
__step ;// 调用父 constructor 的 step 函数

特别声明:本站内容均来自网友提供或互联网,仅供参考,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。