差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

后一修订版
前一修订版
modding:scripting [2022/03/14 14:54] – 创建/转码 硫缺铅modding:scripting [2022/03/19 17:24] (当前版本) – 补充 awa
行 1: 行 1:
 +====== 脚本编写 ======
  
 +Mindustry 使用 JavaScript 作为脚本编写的语言。
 +Mindustry 使用的 JavaScript 基于 Rhino。
 +所以你可以使用 Java 的类。
 +例如:
 +<code js>
 +java.lang.System.out.println("this is a test!");
 +</code>
 +
 +脚本使用 ''%%js%%''
 +的拓展名,被放置在 ''%%scripts/%%''  文件夹。
 +
 +脚本的执行开始于名为 ''%%main.js%%'' 的文件夹,其他脚本可以用''%%require("脚本名")%%''语句导入主文件。典型的设置脚本如下所示:
 +
 +//scripts/main.js//:
 +
 +<code js>
 +require("blocks");
 +require("items");
 +</code>
 +
 +//scripts/blocks.js//:
 +
 +<code js>
 +const myBlock = extend(Conveyor, "terrible-conveyor", {
 +  // 各种字段...
 +  size: 3,
 +  health: 200
 +  //...
 +});
 +</code>
 +
 +//scripts/items.js//:
 +
 +<code js>
 +const terribleium = Item("terribleium");
 +terribleium.color = Color.valueOf("ff0000");
 +//...
 +</code>
 +
 +====== 示例 ======
 +
 +===== 监听事件 =====
 +
 +<code js>
 +// 监听单位被摧毁的事件
 +Events.on(UnitDestroyEvent, event => {
 +  // 如果单位是玩家在屏幕上方显示文字
 +    if(event.unit.isPlayer()){
 +    Vars.ui.hudfrag.showToast("Pathetic.");
 +  }
 +})
 +</code>
 +找到能监听的事件最简单的方法就是看源码: [[https://github.com/Anuken/Mindustry/blob/master/core/src/mindustry/game/EventType.java|Mindustry/blob/master/core/src/mindustry/game/EventType.java]]
 +
 +===== 显示对话框 =====
 +
 +<code js>
 +const myDialog = new BaseDialog("Dialog Title");
 +// 加入“关闭”按钮
 +myDialog.addCloseButton();
 +// 在主体中添加文字
 +myDialog.cont.add("Goodbye.");
 +// 显示对话框
 +myDialog.show();
 +</code>
 +
 +===== 播放自定义声音 =====
 +
 +播放自定义声音很简单,你只需要提供在 ''%%/sounds%%''  里存储的''%%.mp3%%'' 或者 ''%%.ogg%%''文件。
 +
 +在这个例子中,我们存储了 ''%%example.mp3%%'' 在 ''%%/sounds/example.mp3%%''
 +====使用链接库播放声音 ====
 +
 +//scripts/alib.js//:
 +
 +<code js>
 +exports.loadSound = (() => {
 +    const cache = {};
 +    return (path) => {
 +        const c = cache[path];
 +        if (c === undefined) {
 +            return cache[path] = loadSound(path);
 +        }
 +        return c;
 +    }
 +})();
 +</code>
 +
 +//scripts/main.js//:
 +
 +<code js>
 +const lib = require("alib");
 +Events.on(WaveEvent, event => {
 +    // 加载 example.mp3
 +    const mySound = lib.loadSound("example");
 +    // 游戏引擎将会在 (X,Y)处生成声音
 +    mySound.at(1, 1);
 +})
 +</code>
 +
 +%%//%%TODO test these out and add more examples