首页 / JS 脚本手册 / 第一个脚本

第一个脚本

从零写一个显示车速的脚本,跑通完整链路。

目录结构

脚本放在资源包的 assets/<命名空间>/ 下,路径可自定:

你的资源包.zip
└─ assets/
   └─ mypack/
      ├─ mtr_custom_resources.json
      └─ scripts/
         └─ speed.js

写脚本

scripts/speed.js

// 每辆车创建时调用一次
function create(ctx, state, train) {
  state.lastLog = 0;
}

// 每帧调用
function render(ctx, state, train) {
  if (!train.shouldRender()) return;

  var now = Date.now();
  if (now - state.lastLog < 1000) return;
  state.lastLog = now;

  Resources.print(
    train.routeName() + " 开往 " + train.destinationName() +
    " | " + train.speedKmh().toFixed(1) + " km/h" +
    " | 下一站 " + train.nextStationName()
  );
}
render 每帧每车都会跑。 不要在里面做重活,也不要无节流地打日志 —— 一辆 8 编组的车一秒就是几百次调用。 上面用 state.lastLog 限流到每秒一次。

挂到车辆上

mtr_custom_resources.json

{
  "custom_trains": {
    "my_train": {
      "name": "我的列车",
      "base_train_type": "train_20_2",
      "script_files": ["mypack:scripts/speed.js"],
      "engine": "rhino"
    }
  }
}

两种声明方式的完整说明见在资源包中声明

看到输出

  1. 把资源包放进 resourcepacks/ 并启用
  2. F7 重载 RTE 客户端资源(不必退出游戏)
  3. 生成一辆该型号的车,看 logs/latest.log

Resources.print() 的输出带 [Script] 前缀。

改完立即生效

改了 .js 后按 F7 即可重载,无需重启游戏。 脚本报错也在日志里,搜 Error in RTE Resource Pack JavaScript