Minecraft Wiki

除另有声明,转载时均必须注明出处若簡繁轉換出錯,請以遊戲內為準请勇于扩充与修正内容有兴趣逛逛我们的微博沟通交流,欢迎到社区专页需要协助,请在告示板留言

了解更多

Minecraft Wiki
Advertisement
Information icon.svg
此特性为基岩版独有。
Iron Pickaxe JE3 BE2.png
该页面的编辑正在进行中。 讨论

请帮助我们扩充或改进这篇文章。

Ic translate.svg
此条目的(部分)内容需要翻译。

你可以帮助我们来翻译此条目,但请勿使用机器翻译

本条目是基岩版1.12.0的脚本文档。

版本:1.12.0.28

目录

脚本执行系统[]

Minecraft脚本引擎(Minecraft Script Engine)(下面简称脚本引擎)使用的语言是 JavaScript。

玩家可以编写 Javascript 脚本,与行为包绑定在一起来监测游戏中的事件(Event)、对游戏中的事件做出回应,获取、修改实体的组件(Components that an entity have)的数据,以及影响 Minecraft 的其他方面。

演示[]

这些脚本来自 Mojang,有助于入门编写脚本。解压它们来查看代码;或把它们作为 .mcpack 格式的文件,导入游戏并游玩。

演示 最近的更新时间 下载链接
Turn-Based RPG 2019/4/17 https://aka.ms/minecraftscripting_turnbased
Mob Arena 2019/4/17 https://aka.ms/minecraftscripting_mobarena

已知问题[]

下面是Minecraft脚本引擎到目前为止的已知问题的清单。

已知问题 变通的解决方法
来自压缩包的脚本不会被正确加载 在把含脚本的行为包应用于世界之前解压它。如果导入的是拓展名为 .mcpack 的含脚本的行为包,它会自动被解压。
自定义 UI 在 VR 或 MR 模式不工作 目前自定义 UI 只在一般的模式下被启用
自定义 UI 在暂停游戏和继续游戏之间不保持状态 目前没有
退出一个不含脚本的世界并接着进入另一个含脚本的世界,加载的世界可能是错误的 在打开另一个世界之前重启 Minecraft
在濒死的实体(entity)上调用 removeEntity 可能会导致游戏崩溃 请勿在将实体的伤害降低到 0 的帧上调用 removeEntity。“remove” 实体会立即将其删除。 取而代之的是,保存所有濒死的实体并在下一帧清理他们(这种做法的示例,请参见上面的 Turn-Based RPG DEMO)

破坏性的变化[]

随着我们不断改进实验中的脚本 API,我们可能会对 Minecraft 做出使你的脚本出问题的修改。

如果你的脚本的表现不合预期,请查阅该表格。

分类 变化
UI 现在 engine.on 拥有一个facet名字。 为了检查脚本引擎是否启动并将其连接到UI,您需要: engine.on("facet:updated:core.scripting", ...);

完成初始化后,接着: engine.trigger("facet:request", ["core.scripting"]);

组件 现在,对 getComponent 的调用将在返回对象的'data'参数内返回组件的参数。
事件 现在,事件数据对象将事件的参数保存在其'data'参数中。
事件 自定义事件使用前需要先注册。更多信息请查阅 registerEventData 的文档。
事件 自定义事件必须有名字空间,并且不能使用'minecraft'名字空间。 该名字空间仅保留给内置事件。
事件 事件数据现已标准化。 调用 createEventData 创建一个事件数据对象,该对象预先填充了事件的所有字段和默认值。 您需要此事件数据对象来触发任何事件。

准备[]

你希望制作自己的脚本?太好了!这一节列出了最低配置要求和建议配置要求。

注意: 只有 Windows 10 上的 Minecraft 基岩版 支持脚本。如果在不支持脚本的版本上打开含脚本的世界,就会显示不能进入该世界的错误信息。

软件 最低配置要求 建议配置要求
Minecraft Windows 10上的 Minecraft 基岩版 Windows 10上的 Minecraft 基岩版
代码编辑器 Visual Studio Code或其他文本编辑器 安装了“JavaScript 诊断”“JavaScript 和 TypeScript 语言支持”“实时调试器”组件的Visual Studio Community 2019
调试器 Visual Studio Community 2019
其他 原版行为包(可从 https://aka.ms/behaviorpacktemplate 下载) 原版行为包(可从 https://aka.ms/behaviorpacktemplate 下载)
存储容量 1.0 GB 的剩余空间,以供文本编辑器、游戏和脚本占用 1.0 GB 的剩余空间,以供Visual Studio、游戏和脚本占用

开始[]

首先要下载最新的原版行为包(可以从 https://aka.ms/behaviorpacktemplate 下载),然后解压。

要运行的脚本应该放在行为包的 scripts 文件夹(的子文件夹)里,这个文件夹包含两个子文件夹:server 和 client。

  • server:这里的脚本在服务器端运行。生成新的实体,添加组件(Component)和修改实体的组件的代码适合放在这里。
  • client:这里的脚本在客户端运行。回应事件(Event)和处理因玩家而异的事务的代码适合放在这里。

无论是制作客户端脚本还是服务器端脚本,只需要在对应的文件夹中创建一个拓展名为 .js 的空文件,之后在代码编辑器中打开。然后尽情编写代码吧!文件夹中的脚本文件的多少不限,名称也不限。各脚本文件的运行相互独立。

注意:要在某个世界运行脚本,你必须在那个世界启用“使用实验玩法”,因为该功能仍在 Beta 测试阶段。

当进入含客户端脚本的本地世界(Local world)或多人游戏世界(Multiplayer world)时,会有是否同意在你的设备上运行脚本的提示。另外,如果你的包里有客户端脚本,你需要在这个包的 manifest.json 中添加 'client_data' 的模块。这告诉游戏,scripts/client 文件夹中的所有文件需要被发送到客户端。为了获得更多的附加包的 manifest content 的方面的信息,请查阅基岩版附加包文档

文件夹结构

客户端脚本所需的文件夹结构的示例

1 {
2     "description": "Example client scripts module",
3     "type": "client_data",
4     "uuid": "c05a992e-482a-455f-898c-58bbb4975e47",
5     "version": [0, 0, 1]
6 }
vanilla_behavior_pack
|-scripts
|--client
|---myClientScript.js
|--server
|---myServerScript.js
|-manifest.json
|-pack_icon.png

脚本的结构[]

在这一节中,你可以找到用于 Minecraft 脚本引擎的 Javascript 脚本文件的基本结构的简要介绍。如果你希望进一步了解 Javascript 或希望跟随一个基础的教程学习,你可以查看 Mozilla Developer Network 的官方文档:https://developer.mozilla.org/docs/Web/JavaScript

这些在某种程度上(in a way)是脚本的必须部分,但是它们绝不是你只能包含在其中的部分。你可以按照需要创建其他的方法——只需要确保他们在定义之后被调用!

1. 注册脚本文件[]

首先我们需要在脚本执行系统中注册我们的脚本文件。这标志着我们的脚本被建立在游戏的客户端(client)或服务器端(server)线程上。一般来说,你的选择基于你把脚本文件放在了client文件夹里还是server文件夹里。为了完成那件事,只需要在客户端和脚本中的其中一处调用registerSystem并传入 你需要的API 的版本。

参数[]
类型 名称 描述
整数(Integer) majorVersion 这是你的脚本运行所需的 Minecraft 脚本引擎的主要版本
整数(Integer) minorVersion 这是你的脚本运行所需的 Minecraft 脚本引擎的次要版本
示例[]
客户端[]
let sampleClientSystem = client.registerSystem(0, 0);
服务器端[]
let sampleServerSystem = server.registerSystem(0, 0);

2. 脚本执行系统初始化[]

这是注册完成脚本执行系统后立刻被调用的方法(Method)。在世界开始(world start)时它就会运行。你可以使用这个方法来为你的脚本建立(set up)需要的环境:注册自定义组件(Custom component)和自定义事件(Custom event),建立事件监听器(Event listener)等。这会在玩家加入、世界完成“之前”运行。这个函数应被用于初始化变量和建立事件监听器。你不应该在这时(at this point)试图生成(Spawn)实体或与任何实体互动。你也应该避免与UI元素(UI element)互动或向聊天框发送消息,因为这在玩家就绪(ready)之前被调用。

示例[]
sampleSystem.initialize = function() {
	//注册事件数据、注册组件、注册查询、侦听事件
};

3. 脚本执行系统更新[]

这个方法在每个游戏刻(Game tick)被调用。服务器端和客户端每秒共有 20 个游戏刻。这是获取和检查组建的变化,和对组建的变化做出反应的好位置。

示例[]
sampleSystem.update = function() {
	//更新全部内容
};

4. 脚本执行系统关闭[]

这个方法在 Minecraft 脚本引擎关闭的时候被调用。对于客户端来说,这个时候是玩家离开世界的时候;对于服务器端来说,这个时候是最后玩家离开世界的时候。

示例[]
sampleSystem.shutdown = function() {
	//只清理脚本内容
};

调试[]

你的脚本不能运行或不按照期望工作?别担心!我们在 Minecraft 脚本引擎中开发了一些调试工具,来帮助你弄明白你的脚本哪里有问题。如果你是编程新手或进一步了解调试,我们建议你阅读下面的有关用 Visual Studio 调试的文件:https://docs.microsoft.com/visualstudio/debugger

下面介绍了两种弄明白当脚本出问题时发生了什么的方法:游戏内(In-game)调试和实时(Real-time)调试。要进行游戏内调试,只需要游戏和脚本;而要进行实时调试,需要一台 Windows 10 PC 和配置成可以进行实时调试的Visual Studio。

游戏内调试[]

当脚本在游戏中运行时,脚本引擎在出问题时会输出报错消息(Error message)。例如,如果你尝试获取脚本引擎不知道的组件,会收到一个报错信息。要查看所有报错信息,可以打开有所有生成的报错信息的聊天框,还可以打开游戏产生的日志文件(Log file)。日志文件的位置因平台而异,Windows 10 上的基岩版的日志文件位于 %APPDATA%\..\Local\Packages\Microsoft.MinecraftUWP_8wekyb3d8bbwe\LocalState\logs

我们强烈建议你,当你开发脚本时,在你的脚本中开发进一步的的调试消息(Debug message)和工具。这对你弄清楚哪里出问题有帮助。如果你需要更多帮助,可以联系官方 Discord 频道:https://discord.gg/Minecraft

实时调试[]

如果你有一台装有 Visual Studio 的 Windows 10 PC,你可以把 Visual Studio 的调试器附加到 Minecraft 的进程,对脚本进行实时调试。Visual Studio 如果安装有本文 "建议配置要求" 所要求的组件,那么实时调试已被安装并启用了。这个工具会在脚本发生异常(Exception)时显示消息,并使你可以在脚本出问题的行打开 Visual Studio。

除此之外,你还可以手动连接到脚本引擎并调试你的代码。你可以使用远程调试(Remote debugging)来连接到在其他设备上运行的 Minecraft,并对其进行调试。要获得对如何使用远程调试的指导,请查阅 Visual Studio的调试器文档(Visual Studio Debugger documentation)。

首先打开 Visual Studio。如果这是你安装后第一次打开 Visual Studio,我们建议选择将开发设置设为为 “Javascript”,并在收到登录微软账户的提示时登陆微软账户。这些操作建立了有你需要的最重要的工具的 Visual Studio 界面。

打开 Visual Studio 后,启动 Minecraft,然后创建一个开启了实验性玩法的新的世界,并把包含你的脚本的行为包附加(Apply)到这个世界。

创建世界之后,回到 Visual Studio ,点击“调试”菜单,再点击“附加到进程”。打开的窗口中,有一个标着“筛选进程”的搜索框,点击它并输入 “Minecraft”。

一旦列表缩小到只有Minecraft的实例正在运行,就可以通过查看Type列来验证脚本引擎是否正在运行。这指明脚本和x86或x64。

选择那个进程并点击“附加”来将调试器附加到 Minecraft。现在,当下一行脚本代码运行时,可以按暂停键暂停脚本引擎。这样你就可以检查脚本中变量的值,并在代码发生错误时能够立即进入Visual Studio。【警告】:当您点击断点使用调试器一步一步执行代码时,客户端可能会出现超时并断开连接的现象;服务器则可能会断开所有玩家的连接。

脚本 API 对象(Script API object)[]

下面介绍了脚本 API 返回的一些对象(Object)的定义。

实体 JS API 对象(Entity JS API object)[]

类型 属性的名称 描述
字符串(String) __type__ 只读。它指出了对象的类型。值为 "entity""item_entity"
字符串(String) __identifier__ 只读。这是该对象的命名空间 ID,写作 命名空间:名称 的形式。例如,如果 __type__ 值为 "entity" ,且该对象代表的实体是牛,那么 __identifier__ 值为 minecraft:cow
正整数(Positive interger) id 只读。这是所代表的实体的唯一 ID(unique identifier)。

地图 JS API 对象(Level JS API object)[]

类型 属性的名称 描述
字符串(String) __type__ 只读。它指出了对象的类型。值为 "level"
正整数(Positive interger) level_id 只读。这是所代表的地图的唯一 ID。

组件 JS API 对象(Component JS API object)[]

类型 属性的名称 描述
字符串(String) __type__ 只读。它指出了对象的类型。值为 "component"
JavaScript 对象(JavaScript object) data 这是组件的内容。

查询 JS API 对象(Query JS API object)[]

类型 属性的名称 描述
字符串(String) __type__ 只读。它指出了对象的类型。值为 "query"
正整数(Positive interger) query_id 只读。这是所代表的查询的唯一 ID。

堆叠物品 JS API 对象(ItemStack JS API object)[]

类型 属性的名称 描述
字符串(String) __type__ 只读。它指出了对象的类型。值为 "item_stack"
字符串(String) __identifier__ 只读。这是该对象的命名空间ID,写作 命名空间:名称 的形式。例如,如果 __type__ 值为 "entity",且该对象代表的是牛,那么 __identifier__ 值为 minecraft:cow
字符串(String) item 只读。这是所代表的堆叠物品的物品的唯一 ID。
字符串(String) count 只读。这是所代表的堆叠物品的物品数量。

方块 JS API 对象(Block JS API object)[]

类型 属性的名称 描述
字符串(String) __type__ 只读。它指出了对象的类型。值为 "block"
字符串(String) __identifier__ 只读。这是该对象的命名空间ID,写作 命名空间:名称 的形式。例如,如果 __type__ 值为 "block" ,且该对象代表的是基岩,那么 __identifier__ 值为 minecraft:bedrock
JavaScript 对象(JavaScript object) ticking_area 只读。这是被用于获取方块信息的常加载区域 JS API 对象。
JavaScript 对象(JavaScript object) block_position 只读。这是方块的方向,它起唯一 ID 的部分作用。

参数[]

类型 名称 描述
整数(Integer) x x坐标
整数(Integer) y y坐标
整数(Integer) z z坐标

常加载区域 JS API 对象(Ticking area JS API object)[]

常加载区域 JS API 对象共有两种:实体常加载区域 JS API 对象(Entity Ticking area JS API object)和 地图常加载区域 JS API 对象(Level Ticking area JS API object)。当函数要输入一个常加载区域,这两种都可以。

实体常加载区域 JS API 对象(Entity Ticking area JS API object)[]

类型 属性的名称 描述
字符串(String) __type__ 只读。它明确了对象的类型。值为 "entity_ticking_area"
正整数(Positive interger) entity_ticking_area_id 只读。这是所代表的常加载区域的唯一 ID。

地图常加载区域 JS API 对象(Level Ticking area JS API object)[]

类型 属性的名称 描述
字符串(String) __type__ 只读。它明确了对象的类型。值为 "level_ticking_area"
字符串(String) level_ticking_area_id 只读。这是所代表的常加载区域的唯一 ID。

脚本绑定(Script binding)[]

绑定(Binding)是脚本引擎修改游戏中的事物的潜能(capability)。

日志绑定(Logging binding)[]

log(Message)[]

log方法通过服务器端(server)或客户端(client)对象访问,并允许将Message记录到ContentLog文件中。对于 Windows 10 上的基岩版,它位于 %APPDATA%\..\Local\Packages\Microsoft.MinecraftUWP_8wekyb3d8bbwe\LocalState\logs

参数[]
类型 名称 描述
字符串(String) Message 希望发送到日志文件的消息
示例[]

将一段内容发送到日志文件

system.exampleFunction = function() {
	client.log("example log message") 
};

实体绑定(Entity binding)[]

createEntity()[]

使用这个方法可以创建一个不存在这个世界的、没有任何组件(components)的实体。这个实体的Type为"Custom",并且拥有一个空白的标识符(identifier)。这不是一个有效的实体,因为它在这个世界里不存在,只有脚本引擎知道它的存在。

备注: 实体首先在服务端被创建,之后会通知客户端新的实体。注意一点:如果马上把结果的对象发送给客户端, 那么这个实体可能在客户端上就不存在。

返回值[]
类型 描述
实体 JS API 对象(Entity JS API object) object 表示新创建的实体的对象
JavaScript 对象(JavaScript object) null 创建实体时出了问题

createEntity(Type, TemplateIdentifier)[]

创建一个实体并应用指定的以JSON定义的模板。这允许你把已启用的行为包作为基础,快速创建实体。实体被生成到这个世界中,其中包含在指定ID的JSON文件中定义的所有组件、组件组和事件触发器。仅适用于服务器上注册的脚本。注意:实体首先在服务器上创建,然后通知客户端新的实体。请注意,如果您立即将结果对象发送到客户端,那么所创建的实体可能还不存在于客户端上。

参数[]
类型 名称 描述
字符串(String) Type 指定从模板生成的实体的类型(Type)。有效的输入为`entity`和`item_entity`
字符串(String) TemplateIdentifier 这可以是任何已启用的行为包中的实体ID。例如 minecraft:cow 使实体成为JSON中定义的牛
返回值[]
类型 描述
实体 JS API 对象(Entity JS API object) object 表示新创建的实体的对象
JavaScript 对象(JavaScript object) null 创建实体时出了问题

destroyEntity(EntityObject)[]

销毁一个有效的实体。如果实体存在世界上,调用此方法将会完全从世界上删除实体并销毁它,并让对应的实体对象不再可用。你只应该在完成使用后销毁实体并且不再使用它。注意:此方法不会直接杀死实体。调用此方法删除实体不会触发实体死亡事件,实体仅仅是简单地被删除了。

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) EntityObject 来自调用createEntity()方法的对象或来自实体事件的对象
返回值[]
类型 描述
布尔值(Boolean) true 实体被成功销毁
JavaScript 对象(JavaScript object) null 销毁实体时出了问题

isValidEntity(EntityObject)[]

检测给定的的实体对象是否是无效的。

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) EntityObject 来自调用createEntity()方法的对象或来自实体事件的对象
返回值[]
类型 描述
布尔值(Boolean) true 实体在脚本引擎的实体数据库中
布尔值(Boolean) false 实体不在脚本引擎的实体数据库中
JavaScript 对象(JavaScript object) null 确认(validate)实体时出了问题

组件绑定(Component binding)[]

registerComponent(ComponentIdentifier, ComponentData)[]

创建一个只有在脚本中存在的组件。它可以从实体被添加、移除和更新。创建的自定义组件只在脚本引擎运行期间存在。

参数[]
类型 名称 描述
字符串(String) ComponentIdentifier 自定义组件的identifier。It is required to use a namespace so you can uniquely refer to it later without overlapping a name with a built-in component: 例如 'myPack:myCustomComponent'
JavaScript 对象(JavaScript object) ComponentData A JavaScript Object that defines the name of the fields and the data each field holds inside the component.
返回值[]
类型 描述
布尔值(Boolean) true 这个组件注册成功了
JavaScript 对象(JavaScript object) null 注册这个组件时出问题了

createComponent(EntityObject, ComponentIdentifier)[]

创建指定的组件并将它添加到实体。This should only be used with custom components which need to be registered first. If the entity already has the component, this retrieves the component already there instead.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) EntityObject 来自调用createEntity()方法的对象或来自实体事件的对象
字符串(String) ComponentIdentifier The identifier of the component to add to the entity. This is either the identifier of a built-in component (check the Script Components section) or a custom component created with a call to registerComponent()
返回值[]
类型 描述
组件 JS API 对象(Component JS API object) object An object with the following fields, and additionally, all the fields as defined in the component
JavaScript 对象(JavaScript object) null 创建组件时出了问题

hasComponent(EntityObject, ComponentIdentifier)[]

Checks if the given entity has the specified component.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) EntityObject The EntityObject that was retrieved from a call to createEntity() or retrieved from an event
字符串(String) ComponentIdentifier The identifier of the component to check on the entity. This is either the identifier of a built-in component (check the Script Components section) or a custom component created with a call to registerComponent()
返回值[]
类型 描述
布尔值(Boolean) true The EntityObject has the component
布尔值(Boolean) false The EntityObject doesn't have the component
JavaScript 对象(JavaScript object) null An unknown component was passed in or something else went wrong when checking if the EntityObject had the component

getComponent(EntityObject, ComponentIdentifier)[]

Looks for the specified component in the entity. If it exists, retrieves the data from the component and returns it.;

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) EntityObject The EntityObject that was retrieved from a call to createEntity() or retrieved from an event
字符串(String) ComponentIdentifier The identifier of the component to retrieve from the entity. This is either the identifier of a built-in component (check the Script Components section) or a custom component created with a call to registerComponent()
返回值[]
类型 描述
组件 JS API 对象(Component JS API object) object An object with the following fields, and additionally, all the fields as defined in the component

Component JS API Object

类型 名称 描述
字符串(String) __type__ 只读。 This defines the type of object. Value is: "component".
JavaScript 对象(JavaScript object) data This is the content of the component.
JavaScript 对象(JavaScript object) null 实体没有组件或获取组件时出了问题

applyComponentChanges(EntityObject, ComponentObject)[]

Applies the component and any changes made to it in script back to the entity. What this means for each component can be slightly different: it makes the component reload on the entity with the new data as if it had just been added to the entity.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) EntityObject The entity object that we are applying the component changes to
组件 JS API 对象(Component JS API object) ComponentObject The component object retrieved from the entity that was returned by either createComponent() or getComponent()
返回值[]
类型 描述
布尔值(Boolean) true The component was successfully updated
JavaScript 对象(JavaScript object) null 更新组件时出了问题

destroyComponent(EntityObject, ComponentIdentifier)[]

Removes the specified component from the given entity. If the entity has the component, it is removed. Currently this only works with custom components and can't be used to remove components defined for an entity in JSON.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) EntityObject The EntityObject that was retrieved from a call to createEntity() or retrieved from an event
字符串(String) ComponentIdentifier The identifier of the component to remove from the entity. This is either the identifier of a built-in component (check the Script Components section) or a custom component created with a call to registerComponent()
返回值[]
类型 描述
布尔值(Boolean) true The component was successfully removed from the entity
JavaScript 对象(JavaScript object) null 实体没有组件或移除组件时出了问题

事件绑定(Event binding)[]

These are the bindings used to handle events. For a list of events you can react to or trigger, check the Events section of this document.

registerEventData(EventIdentifier, EventData)[]

Registers the Event to the script engine. This allows you to create Event Data by calling createEventData and have it initialized with the correct default data and fields. Only custom events need to be registered.

参数[]
类型 名称 描述
字符串(String) EventIdentifier This is the identifier of the custom event we are registering. The namespace is required and can't be set to minecraft.
JavaScript 对象(JavaScript object) EventData The JavaScript object with the correct fields and default values for the event
返回值[]
类型 描述
布尔值(Boolean) true Successfully registered the event data
JavaScript 对象(JavaScript object) null 注册监听事件时出了问题

createEventData(EventIdentifier)[]

Creates an object with all the required fields and default data for the specified event. If the event is a custom event, it needs to have been previously registered.

参数[]
类型 名称 描述
字符串(String) EventIdentifier This is the identifier of the custom event we are registering. The namespace is required and can't be set to minecraft.
返回值[]
类型 描述
JavaScript 对象(JavaScript object) The object containing the event data
JavaScript 对象(JavaScript object) null 注册监听事件时出了问题

listenForEvent(EventIdentifier, CallbackObject)[]

Allows you to register a JavaScript object that gets called whenever the specified event is broadcast. The event can either be a built-in event or an event specified in script.

参数[]
类型 名称 描述
字符串(String) EventIdentifier This is the identifier of the event to which we want to react. Can be the identifier of a built-in event or a custom one from script
JavaScript 对象(JavaScript object) CallbackObject The JavaScript object to be called whenever the event is broadcast
返回值[]
类型 描述
布尔值(Boolean) true Successfully registered to listen for the event
JavaScript 对象(JavaScript object) null 注册监听事件时出了问题

broadcastEvent(EventIdentifier, EventData)[]

Allows you to trigger an event with the desired data from script. Anything that signed up to listen for the event is notified and the given data delivered to them.

参数[]
类型 名称 描述
字符串(String) EventIdentifier This is the identifier of the event we want to react to. Can be the identifier of a built-in event or a custom one from script
JavaScript 对象(JavaScript object) EventData The data for the event. You can create a new JavaScript Object with the parameters you want to pass in to the listener and the engine takes care of delivering the data to them
返回值[]
类型 描述
布尔值(Boolean) true Successfully broadcasted the event
JavaScript 对象(JavaScript object) null 广播(broadcast)事件时出了问题

实体查询(Entity query)绑定[]

Entity Queries are a way for you to filter for entities based on their components. Once you have registered a query, you can request all the entities that are captured by it. Entity Queries only ever return entities that are currently active in the level. If your query extends into chunks that are not currently loaded, entities there are not included in the query.

registerQuery()[]

Allows you to register a query. A query contains all entities that meet the filter requirement. No filters are added by default when you register a query so it captures all entities.

返回值[]
类型 描述
查询JS API对象(Query JS API object) object An object containing the ID of the query
JavaScript 对象(JavaScript object) null 创建查询时出了问题
示例[]

注册一个“实体查询”

1 var simple_query = {};
2 system.initialize = function() {
3 	simple_query = this.registerQuery(); 
4 };

registerQuery(Component, ComponentField1, ComponentField2, ComponentField3)[]

Allows you to register a query that show only entities that have the given component and define which fields of that component are used as a filter when getting the entities from the query. You can either provide just the component identifier, or the component identifier and the name of 3 properties on that component to be tested (If you do specify property names, you must specify 3).

参数[]
类型 名称 默认值 描述
字符串(String) Component This is the identifier of the component that is used to filter entities when
字符串(String) ComponentField1 "x" This is the name of the first field of the component that we want to filter entities by. By default this is set to x.
字符串(String) ComponentField2 "y" This is the name of the second field of the component that we want to filter entities by. By default this is set to y.
字符串(String) ComponentField3 "z" This is the name of the third field of the component that we want to filter entities by. By default this is set to z.
返回值[]
类型 描述
查询JS API对象(Query JS API object) object An object containing the ID of the query
JavaScript 对象(JavaScript object) null 创建查询时出了问题
示例[]

注册一个“实体查询”

1 var spacial_query = {};
2 system.initialize = function() {
3 	spacial_query = this.registerQuery("minecraft:position", "x", "y", "z"); 
4 };

addFilterToQuery(Query, ComponentIdentifier)[]

By default no filters are added. This allows queries to capture all entities.

参数[]
类型 名称 描述
查询JS API对象(Query JS API object) Query The object containing the ID of the query that you want to apply the filter to
字符串(String) ComponentIdentifier This is the identifier of the component that is added to the filter list. Only entities that have that component are listed in the query
示例[]
Query Filtering
1 var filtered_query = {};
2 system.initialize = function() {
3 	filtered_query = this.registerQuery(); 
4 	this.addFilterToQuery(filtered_query, "minecraft:explode"); 
5 };

getEntitiesFromQuery(Query)[]

Allows you to fetch the entities captured by a query.<

参数[]
类型 名称 描述
查询JS API对象(Query JS API object) Query This is the query you registered earlier using registerQuery()
返回值[]
类型 描述
序列(Array) 序列 An array of EntityObjects representing the entities found within the query
JavaScript 对象(JavaScript object) null 创建实体时出了问题
示例[]
Entity Fetching
1 system.update = function() {
2 	let all_entities = this.getEntitiesFromQuery(simple_query);
3 	let exploding_creepers = this.getEntitiesFromQuery(filtered_query);
4 };

getEntitiesFromQuery(Query, ComponentField1_Min, ComponentField2_Min, ComponentField3_Min, ComponentField1_Max, ComponentField2_Max, ComponentField3_Max)[]

Allows you to fetch the entities captured by a query that was created with a component filter built-in. The only entities returned are those entities that have the component that was defined when the query was registered and that have a value in the three fields on that component that were defined in the query within the values specified in the call to getEntitiesFromQuery.

参数[]
类型 名称 描述
查询JS API对象(Query JS API object) Query This is the query you created earlier using registerQuery(...)
Decimal ComponentField1_Min The minimum value that the first component field needs to be on an entity for that entity to be included in the query
Decimal ComponentField2_Min The minimum value that the second component field needs to be on an entity for that entity to be included in the query
Decimal ComponentField3_Min The minimum value that the third component field needs to be on an entity for that entity to be included in the query
Decimal ComponentField1_Max The maximum value that the first component field needs to be on an entity for that entity to be included in the query
Decimal ComponentField2_Max The maximum value that the second component field needs to be on an entity for that entity to be included in the query
Decimal ComponentField3_Max The maximum value that the third component field needs to be on an entity for that entity to be included in the query
返回值[]
类型 描述
序列(Array) 序列 An array of EntityObjects representing the entities found within the query
JavaScript 对象(JavaScript object) null 创建实体时出了问题
示例[]
Entity Fetching
1 system.update = function() {
2 	let player_pos_component = this.getComponent(player, "minecraft:position");
3 	let pos = player_pos_component.data;
4 	let spacial_query = this.registerQuery("minecraft:position", "x", "y", "z");
5 	let entities_near_player = this.getEntitiesFromQuery(spacial_query, pos.x - 10, pos.y - 10, pos.z - 10, pos.x + 10, pos.y + 10, pos.z + 10);
6 };

命令(斜杠命令)绑定[]

您可以从脚本中使用传统的斜杠命令系统。目前可以通过触发事件[trigger an event]("minecraft:execute_command")或使用executeCommand绑定[binding]。脚本中的命令仅限于服务器脚本,目前无法从客户端运行。

executeCommand(Command,Callback)[]

允许您在服务器上执行斜杠命令。该指令将在当前帧结束时被查询并执行。命令输出的所有数据都在JavaScript对象上编译,并发送到第二个参数中指定的回调对象。

参数[]
类型 名称 描述
字符串(String) Command The slash command to run
JSON 对象(JSON Object) Callback The JavaScript object called after the command executes
示例[]
1 system.executeCommand("/fill ~ ~ ~ ~100 ~5 ~50 stone", (commandResultData) => this.commandCallback(commandResultData));
2 
3 system.commandCallback = function (commandResultData) {
4 	let eventData = this.createEventData("minecraft:display_chat_event");
5 	if (eventData) {
6 		eventData.data.message = message;
7 		this.broadcastEvent("minecraft:display_chat_event", "Callback called! Command: " + commandResultData.command + " Data: " + JSON.stringify(commandResultData.data, null, "    ") );
8 	}
9 };

方块绑定(Block binding)[]

These functions define how you interact with blocks.

getBlock(Ticking Area, x, y, z)[]

Allows you to get a block from the world when provided an x, y, and z position. The block must be within a ticking area.

参数[]
类型 名称 描述
常加载区域JS API对象(Ticking area JS API object) Ticking Area The ticking area the block is in
整数(Integer) x The x position of the block you want
整数(Integer) y The y position of the block you want
整数(Integer) z The z position of the block you want
返回值[]
类型 描述
方块JS API对象(Block JS API object) object An object containing the block
JavaScript 对象(JavaScript object) null 检索方块时出了问题

getBlock(Ticking Area, PositionObject)[]

Allows you to get a block from the world when provided a JavaScript object containing a position. The block must be within a ticking area.

参数[]
类型 名称 描述
常加载区域JS API对象(Ticking area JS API object) Ticking Area The ticking area the block is in
JavaScript 对象(JavaScript object) PositionObject A JavaScript object with the x, y, and z position of the block you want
参数[]
类型 名称 描述
整数(Integer) x The x position
整数(Integer) y The y position
整数(Integer) z The z position
返回值[]
类型 描述
方块JS API对象(Block JS API object) object An object containing the block
JavaScript 对象(JavaScript object) null 检索方块时出了问题

getBlocks(Ticking Area, x min, y min, z min, x max, y max, z max)[]

Allows you to get an array of blocks from the world when provided a minimum and maximum x, y, and z position. The blocks must be within a ticking area.

参数[]
类型 名称 描述
常加载区域JS API对象(Ticking area JS API object) Ticking Area The ticking area the blocks are in
整数(Integer) x min The minimum x position of the blocks you want
整数(Integer) y min The minimum y position of the blocks you want
整数(Integer) z min The minimum z position of the blocks you want
整数(Integer) x max The maximum x position of the blocks you want
整数(Integer) y max The maximum y position of the blocks you want
整数(Integer) z max The maximum z position of the blocks you want
返回值[]
类型 描述
序列(Array) 序列 A 3D array of block objects. Indexs are the blocks positions relative to the min position given
JavaScript 对象(JavaScript object) null 检索方块时出了问题

getBlocks(Ticking Area, Minimum PositionObject, Maximum PositionObject)[]

Allows you to get an array of blocks from the world when provided a minimum and maximum position. The blocks must be within a ticking area.

参数[]
类型 名称 描述
常加载区域JS API对象(Ticking area JS API object) Ticking Area The ticking area the blocks are in
JavaScript 对象(JavaScript object) Minimum PositionObject A JavaScript object with the minimum x, y, and z position of the blocks you want
参数[]
类型 名称 描述
整数(Integer) x The x position
整数(Integer) y The y position
整数(Integer) z The z position
JavaScript 对象(JavaScript object) Maximum PositionObject A JavaScript object with the maximum x, y, and z position of the blocks you want
参数[]
类型 名称 描述
整数(Integer) x The x position
整数(Integer) y The y position
整数(Integer) z The z position
返回值[]
类型 描述
序列(Array) 序列 A 3D array of block objects. Indexs are the blocks positions relative to the min position given
JavaScript 对象(JavaScript object) null 检索方块时出了问题

脚本组件(script component)[]

This is the documentation for the attributes, properties, and components available from the Minecraft Script Engine.

There are two kinds of components: server components and client components. We go into more detail on what they are in their respective sections below.

Components can be added, retrieved, updated, and removed from entities. They do not exist on their own. Currently only user-defined components can be added and removed from entities. A component must be in an entity in order to retrieve or update it.

Check the Script Engine Bindings section to see how to add, remove, retrieve, and update components. This section deals with the specific API of each component.

Level components[]

These are the components that belong to the level. They can only belong on the level object and cannot be removed from it. You can get the components and change their data through the global server object.

let levelComponent = this.getComponent(server.level, "minecraft:example_level_component");

minecraft:ticking_areas[]

This component gives access to the static ticking areas in the level. The component contains an array of ticking areas. The ticking areas can be accessed by name or by UUID if they were not given a name.

minecraft:weather[]

The weather component allows users to change the level's weather. Rain and lightning levels can be changed independently and the default weather cycle can be turned off completely.

参数[]
类型 名称 描述
布尔值(Boolean) do_weather_cycle This is the world option that determines if the vanilla weather cycle is used
Decimal rain_level A value between 0 and 1 that determains how heavy the rainfall is
整数(Integer) rain_time How long it rains, in ticks
Decimal lightning_level A value between 0 and 1 that determines how much lightning and thunder there is
整数(Integer) lightning_time How long lightning and thunder lasts, in ticks

服务器组件(server component)[]

These are the components that run on the server and are synced with all the clients (players) in the world.

As much as possible, the API of each component matches its JSON counterpart (with some differences noted).

minecraft:armor_container[]

This component represents the armor contents of an entity. The component contains an array of ItemStack JS API Objects representing each slot in the armor container. Note: Currently items and containers are read-only. Slots are ordered from head to feet.

 1 // This example checks the players helmet armor slot for a specific item after the player attacks an entity.
 2 system.listenForEvent("minecraft:player_attacked_entity", function(eventData) {
 3     // Get the players armor container
 4     let playerArmor = system.getComponent(eventData.data.player, "minecraft:armor_container");
 5     // Get the players helmet
 6     let playerHelmet = playerArmor.data[0];
 7     // Destroy the attacked entity if the player has a gold helmet equipped
 8     if (playerHelmet.item == "minecraft:golden_helmet") {
 9         system.destroyEntity(eventData.data.attacked_entity);
10     }
11 });

minecraft:attack[]

This component controls the Attack Damage attribute from the entity. It allows you to change the current minimum and maximum values. Once the changes are applied, the current attack of the entity is reset to the minimum specified. With the minimum and maximum changed to the values specified. Any buffs or debuffs are left intact.

参数[]
类型 名称 默认值 描述
Range [a, b] damage Range of the random amount of damage the melee attack deals. A negative value can heal the entity instead of hurting it
参数[]
类型 名称 默认值 描述
Decimal range_min 0.0 The minimum amount of damage the entity can deal
Decimal range_max 0.0 The maximum amount of damage the entity can deal

minecraft:collision_box[]

Controls the collision box of the entity. When changes to the component are applied the entity's collision box is immediately updated to reflect the new dimensions. WARNING: If the change of the collision box dimensions would cause the entity to be inside a block, the entity might become stuck there and start suffocating.

参数[]
类型 名称 默认值 描述
Decimal width 1.0 Width and Depth of the collision box in blocks. A negative value is assumed to be 0
Decimal height 1.0 Height of the collision box in blocks. A negative value is assumed to be 0

minecraft:damage_sensor[]

Defines an array of damages and how the entity reacts to them - including whether the entity ignores that damage or not. Currently Minecraft triggers can't be properly serialized so any existing triggers are completely replaced when applyComponentChanges().

参数[]
类型 名称 默认值 描述
List on_damage List of triggers with the events to call when taking this specific kind of damage, allows specifying filters for entity definitions and events
布尔值(Boolean) deals_damage true If true, the damage dealt to the entity reduces its health; set to false to make the entity ignore that damage
字符串(String) cause Type of damage that triggers this set of events
1 // This example causes an entity (in this case, a creeper) to start exploding when the player attacks it.
2 // Note: the entity must have the damage_sensor component and the associated events defined in their JSON description.
3 this.listenForEvent("minecraft:player_attacked_entity", function(eventData) {
4 	let damageSensorComponent = serverSystem.getComponent(eventData.attacked_entity, "minecraft:damage_sensor");
5 	damageSensorComponent.data[0].on_damage = { event:"minecraft:start_exploding", filters:[{test:"has_component", operator:"==", value:"minecraft:breathable"}] };
6 	serverSystem.applyComponentChanges(eventData.attacked_entity, damageSensorComponent);
7 });

minecraft:equipment[]

Defines the loot table the entity uses to defines its equipment. Once the changes are applied, the equipment is re-rolled and a new set of equipment is chosen for the entity.

参数[]
类型 名称 默认值 描述
字符串(String) table The file path to the equipment table, relative to the behavior pack's root
List slot_drop_chance A list of slots with the chance to drop an equipped item from that slot

minecraft:equippable[]

Defines how many and what items the entity can be equipped with.

slots

List of slots and the item that can be equipped

参数[]
类型 名称 默认值 描述
整数(Integer) slot 0 The slot number of this slot
List accepted_items The list of items that can go in this slot
字符串(String) item Identifier of the item that can be equipped for this slot
字符串(String) interact_text Text to be displayed when the entity can be equipped with this item when playing with Touch-screen controls
字符串(String) on_equip Event to trigger when this entity is equipped with this item
字符串(String) on_unequip Event to trigger when this item is removed from this entity

minecraft:explode[]

Controls the entity's explosion, timer until the explosion, and whether the timer is counting down or not.

参数[]
类型 名称 默认值 描述
Range [a, b] fuseLength [0.0, 0.0] The range for the random amount of time the fuse burns before exploding, a negative value means the explosion is immediate
Decimal power 3.0 The radius of the explosion in blocks and the amount of damage the explosion deals
Decimal maxResistance Infinite A block's explosion resistance is capped at this value when an explosion occurs
布尔值(Boolean) fuseLit false If true, the fuse is already lit when this component is added to the entity
布尔值(Boolean) causesFire false If true, blocks in the explosion radius are set on fire
布尔值(Boolean) breaks_blocks true If true, the explosion destroys blocks in the explosion radius
布尔值(Boolean) fireAffectedByGriefing false If true, whether the explosion causes fire is affected by the mob griefing game rule
布尔值(Boolean) destroyAffectedByGriefing false If true, whether the explosion breaks blocks is affected by the mob griefing game rule

minecraft:hand_container[]

This component represents the contents of an entity's hands. The component contains an array of ItemStack JS API Objects representing each slot in the hand container. Note: Currently items and containers are read-only. Slot 0 is main-hand Slot 1 is off-hand.

 1 // This example checks the players offhand slot for a specific item after the player attacks an entity.
 2 system.listenForEvent("minecraft:player_attacked_entity", function(eventData) {
 3     // Get the players hand container
 4     let handContainer = system.getComponent(eventData.data.player, "minecraft:hand_container");
 5     // Get the players offhand item
 6     let offhandItem = handContainer.data[1];
 7     // Destroy the attacked entity if the player has a totem in their offhand
 8     if (offhandItem.item == "minecraft:totem") {
 9         system.destroyEntity(eventData.data.attacked_entity);
10     }
11 });

minecraft:healable[]

Defines how the entity can be healed by the player. This doesn't control how much health the entity can have; you must use the Health component for that instead.

参数[]
类型 名称 默认值 描述
序列(Array) items The array of items that can be used to heal this entity
参数[]
类型 名称 默认值 描述
字符串(String) item Item identifier that can be used to heal this entity
整数(Integer) heal_amount 1 The amount of health this entity gains when fed this item
Minecraft Filter filters The filter group that defines the conditions for using this item to heal the entity
布尔值(Boolean) force_use false Determines if item can be used regardless of entity being at full health
Minecraft Filter filters The filter group that defines the conditions for this trigger

minecraft:health[]

定义实体当前生命值和最大生命值,修改此组件并应用回实体之后,实体生命值会发生改变。如果生命值改变之后小于等于0,实体将会死亡。

参数[]
类型 名称 默认值 描述
整数(Integer) value 1 实体当前生命值
整数(Integer) max 10 实体最大生命值

minecraft:hotbar_container[]

This component represents the hotbar contents of a player. The component contains an array of ItemStack JS API Objects representing each slot in the hotbar. Note: Currently items and containers are read-only. Slots are ordered left to right.

 1 // This example check sthe players first hotbar item slot for a specific item after the player attacks an entity.
 2 system.listenForEvent("minecraft:player_attacked_entity", function(eventData) {
 3     // Get the players hotbar
 4     let playerHotbar = system.getComponent(eventData.data.player, "minecraft:hotbar_container");
 5     // Get the item at the first slot in the hotbar
 6     let firstHotbarSlot = playerHotbar.data[0];
 7     // Destroy the attacked entity if the player has an apple in their first hotbar slot
 8     if (firstHotbarSlot.item == "minecraft:apple") {
 9         system.destroyEntity(eventData.data.attacked_entity);
10     }
11 });

minecraft:interact[]

Defines the ways the player can interact with the entity to which this component is applied.

参数[]
类型 名称 默认值 描述
Array spawn_entities An array of entity identifiers to spawn when the interaction occurs
字符串(String) on_interact An event identifier to fire when the interaction occurs
JSON 对象(JSON Object) particle_on_start Particle effect to be triggered at the start of the interaction
参数[]
类型 名称 默认值 描述
字符串(String) particle_type The type of particle to be spawned
Decimal particle_y_offset 0.0 Offsets the particle this amount in the y direction
布尔值(Boolean) particle_offset_towards_interactor false Whether or not the particle appears closer to who performed the interaction
Decimal cooldown 0.0 Time in seconds before this entity can be interacted with again
布尔值(Boolean) swing false If true, the player does the 'swing' animation when interacting with this entity
布尔值(Boolean) use_item false If true, the interaction uses an item
整数(Integer) hurt_item 0 The amount of damage the item takes when used to interact with this entity. A value of 0 means the item does not lose durability
字符串(String) interact_text Text to show when the player is able to interact in this way with this entity when playing with Touch-screen controls
JSON 对象(JSON Object) add_items Loot table with items to add to the player's inventory upon successful interaction
参数[]
类型 名称 默认值 描述
字符串(String) table File path, relative to the behavior pack's path, to the loot table file
JSON 对象(JSON Object) spawn_items Loot table with items to drop on the ground upon successful interaction
参数[]
类型 名称 默认值 描述
字符串(String) table File path, relative to the behavior pack's path, to the loot table file
字符串(String) transform_to_item The item used transforms to this item upon successful interaction. Format: itemName:auxValue
Array play_sounds An array of sound identifiers to play when the interaction occurs

minecraft:inventory[]

Defines the entity's inventory (size, restrictions, etc.). Currently this does not allow changing the entity's inventory contents.

参数[]
类型 名称 默认值 描述
字符串(String) container_type none Type of container this entity has. Can be horse, minecart_chest, minecart_hopper, inventory, container or hopper
整数(Integer) inventory_size 5 Number of slots the container has
布尔值(Boolean) can_be_siphoned_from false If true, the contents of this inventory can be removed by a hopper
布尔值(Boolean) private false If true, only the entity can access the inventory
布尔值(Boolean) restrict_to_owner false If true, the entity's inventory can only be accessed by its owner or itself
整数(Integer) additional_slots_per_strength 0 Number of slots that this entity can gain per extra strength

minecraft:inventory_container[]

This component represents the inventory contents of an entity. The component contains an array of ItemStack JS API Objects representing each slot in the inventory. Note: Currently items and containers are read-only.Slot 0-8 is the hotbar, 9-17 is the top row of the player's inventory, 18-26 is the middle row, 27-35 is the bottom row.

 1 // This example checks the players third inventory item slot for a specific item after the player attacks an entity.
 2 system.listenForEvent("minecraft:player_attacked_entity", function(eventData) {
 3     // Get the players inventory
 4     let playerInventory = system.getComponent(eventData.data.player, "minecraft:inventory_container");
 5     // Get the item at the third slot in the inventory
 6     let thirdItemSlot = playerInventory.data[2];
 7     // Destroy the attacked entity if the player has an apple in their third item slot
 8     if (thirdItemSlot.item == "minecraft:apple") {
 9         system.destroyEntity(eventData.data.attacked_entity);
10     }
11 });

minecraft:lookat[]

Makes the entity look at another entity. Once applied, if an entity of the specified type is nearby and can be targeted the entity turns toward it.

参数[]
类型 名称 默认值 描述
布尔值(Boolean) setTarget true If true, this entity sets the attack target as the entity that looked at it
Decimal searchRadius 10.0 Maximum distance this entity can look for another entity looking at it
布尔值(Boolean) mAllowInvulnerable false If true, invulnerable entities (e.g. Players in creative mode) are considered valid targets
Range [a, b] look_cooldown [0.0, 0.0] The range for the random amount of time during which the entity is 'cooling down' and won't get angered or look for a target
Minecraft Filter filters player Defines the entities that can trigger this component
字符串(String) look_event The event identifier to run when the entities specified in filters look at this entity

minecraft:nameable[]

Nameable component describes an entity's ability to be named using a nametag and whether the name shows up or not once applied. Additionally, scripting allows setting the name of the entity directly with the property 'name'.

参数[]
类型 名称 默认值 描述
JSON 对象(JSON Object) name_actions Describes the special names for this entity and the events to call when the entity acquires those names
参数[]
类型 名称 默认值 描述
字符串(String) on_named Event to be called when this entity acquires the name specified in 'name_filter'
List name_filter List of special names that cause the events defined in 'on_named' to fire
字符串(String) default_trigger Trigger to run when the entity gets named
布尔值(Boolean) alwaysShow false If true, the name is always be shown
布尔值(Boolean) allowNameTagRenaming true If true, this entity can be renamed with name tags
字符串(String) name The current name of the entity, empty if the entity hasn't been named yet, making this non-empty applies the name to the entity

minecraft:position[]

該組件使您可以控制實體在世界上的位置。 使用後,實體將被傳送到指定的新位置。

参数[]
类型 名称 默认值 描述
Decimal x 0.0 Position along the X-Axis (east-west) of the entity
Decimal y 0.0 Position along the Y-Axis (height) of the entity
Decimal z 0.0 Position along the Z-Axis (north-south) of the entity

minecraft:rotation[]

This component allows you to control an entity's current rotation in the world as well as the entity's head rotation. Once applied, the entity is rotated as specified.

参数[]
类型 名称 默认值 描述
Decimal x 0.0 Controls the head rotation looking up and down
Decimal y 0.0 Controls the body rotation parallel to the floor

minecraft:shooter[]

Defines the entity's ranged attacks. This doesn't allow the entity to use a ranged attack: it only defines what kind of projectile it shoots.

参数[]
类型 名称 默认值 描述
字符串(String) def Entity identifier to use as projectile for the ranged attack. The entity must have the projectile component to be able to be shot as a projectile
整数(Integer) auxVal -1 ID of the Potion effect to be applied on hit

minecraft:spawn_entity[]

Controls the entity's ability to spawn an entity or an item. This is similar to the chicken's ability to lay eggs after a set amount of time.

参数[]
类型 名称 默认值 描述
布尔值(Boolean) should_leash false If true, this the spawned entity is leashed to the parent
整数(Integer) num_to_spawn 10 The number of entities of this type to spawn each time that this triggers
整数(Integer) min_wait_time 300 Minimum amount of time to randomly wait in seconds before another entity is spawned
整数(Integer) max_wait_time 600 Maximum amount of time to randomly wait in seconds before another entity is spawned
字符串(String) spawn_sound plop Identifier of the sound effect to play when the entity is spawned
字符串(String) spawn_item egg Item identifier of the item to spawn
字符串(String) spawn_entity Identifier of the entity to spawn, leave empty to spawn the item defined above instead
字符串(String) spawn_method born Method to use to spawn the entity
字符串(String) spawn_event minecraft:entity_born Event to call when the entity is spawned
Minecraft Filter filters If present, the specified entity spawns only if the filter evaluates to true
布尔值(Boolean) single_use false If true, this component spawns the specified entity only once

minecraft:teleport[]

This controls the entity's ability to teleport itself (similar to the Enderman). If you wish to teleport the entity once use the Position component instead.

参数[]
类型 名称 默认值 描述
布尔值(Boolean) randomTeleports true If true, the entity teleports randomly
Decimal minRandomTeleportTime 0.0 Minimum amount of time in seconds between random teleports
Decimal maxRandomTeleportTime 20.0 Maximum amount of time in seconds between random teleports
数组(Vector)[a, b, c] randomTeleportCube [32.0, 16.0, 32.0] Entity teleports to a random position within the area defined by this cube
Decimal targetDistance 16.0 Maximum distance the entity can teleport when chasing a target
Decimal target_teleport_chance 1.0 The chance (0.0 to 1.0, where 1.0=100%) that the entity can teleport
Decimal lightTeleportChance 0.01 Modifies the chance that the entity can teleport if the entity is in daylight
Decimal darkTeleportChance 0.01 Modifies the chance that the entity can teleport if the entity is in darkness

minecraft:tick_world[]

The tick world component is a read-only component that allows users to access the ticking areas on entities as well as the ticking area's data.

参数[]
类型 名称 描述
整数(Integer) radius The radius in chunks of the ticking area
Decimal distance_to_players distance_to_players
布尔值(Boolean) never_despawn Whether or not this ticking area despawns when a player is out of range
Entity Ticking Area JS API Object ticking_area The ticking area entity that is attached to this entity

客户端组件(client component)[]

These components only run on the client where the script ran and can only be used from client scripts.

minecraft:molang[]

The MoLang component gives access to the MoLang variables in an entity. To learn more about MoLang varibles review the add-on documentation. In scripts, you can get and set these varibles that are defined in the entity's JSON files. Because of how the MoLang variables are formatted (variable.isgrazing for example) you must use the [] operator on the object to access the variable. The example below shows how to use the [] operator to access the variable.

示例
1 let molangComponent = this.createComponent(entity, "minecraft:molang"); 
2 molangComponent["variable.molangexample"] = 1.0; 
3 this.applyComponentChanges(molangComponent);

方块组件(block component)[]

These components are only found on block objects and can only be on block objects

minecraft:blockstate[]

This component contains all the blockstates on a block object. Blockstates control all different aspects of blocks from their orientation to the type of wood they are. Blockstates are represented by numbers, bools, or strings. Please see the Blockstates Documentation to see the valid values for each state. This component allows for the getting and setting of these states.

示例
1 let blockstateComponent = this.getComponent(block, "minecraft:blockstate");
2 blockstateComponent.data.coral_color = "blue";
3 this.applyComponentChanges(block, blockstateComponent);

用户定义的组件(User-Defined Components)[]

User-Defined components are a special kind of component that can be defined in script and no built-in game system acts on it. The component needs to be registered with the Script Engine by giving it a name and a set of fields in the format name:value. Once applied, the component behaves like any of the built-in components: you can get it from an entity, modify its values, and apply the changes. Currently, user-Defined components are the only components that can be dynamically added and removed from an entity using scripts. They don't need to be previously defined in an entity's JSON file. In the current version, these components are not saved out or loaded back in: they exist only while the entity is there and need to be added back when reloading the level.

示例

组件注册(Component Registration)

1 this.registerComponent("myNamespace:myComponent", { myString: "TamerJeison", myInt: 42, myFloat: 1.0, myArray: [1, 2, 3] });

脚本事件(Script events)[]

下面介绍了可以在脚本中监听和回应的事件。

客户端事件(Client events)[]

Listening events[]

The following Minecraft events are events the Script Engine is listening for and to which you can react in scripts.

minecraft:client_entered_world[]

This event is fired whenever a player joins the world. The event data contains the player entity object.

参数[]
类型 名称 描述
Entity JS API Object player The player entity that joined the world
minecraft:hit_result_changed[]

This event is triggered whenever the reticle changes from pointing at a block or air to pointing at an entity and the other way around. Up to 1000 blocks away.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The entity that was hit or null if it fired when moving off of an entity
数组(Vector)[a, b, c] position The position of the entity that was hit or null if it fired when moving off an entity
示例
1 system.initialize = function() {
2 	this.listenForEvent("minecraft:hit_result_changed", (eventData) => this.onPick(eventData)); 
3 };
1 system.onPick = function(eventData) { 
2 	if (eventData.position !== null) { 
3 		this.broadcastEvent("minecraft:display_chat_event", "Pick at x:" + eventData.position.x + " y:" + eventData.position.y + " z:" + eventData.position.z); 
4 	} 
5 };
minecraft:hit_result_continuous[]

This event is triggered every update and tells you what entity the reticle is pointing to in the world up to 1000 blocks away.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The entity that was hit or null if it not pointing at an entity
数组(Vector)[a, b, c] position The position of the entity that was hit or block that was hit
示例
1 system.initialize = function() {
2 	this.listenForEvent("minecraft:hit_result_continuous", (eventData) => this.onPick(eventData)); 
3 };
1 system.onPick = function(eventData) { 
2 	if (eventData.position !== null) { 
3 		this.broadcastEvent("minecraft:display_chat_event", "Pick at x:" + eventData.position.x + " y:" + eventData.position.y + " z:" + eventData.position.z); 
4 	} 
5 };
minecraft:pick_hit_result_changed[]

This event is triggered whenever the mouse pointer changes from pointing at a block or air to pointing at an entity and the other way around. Up to 1000 blocks away.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The entity that was hit or null if it fired when moving off of an entity
数组(Vector)[a, b, c] position The position of the entity that was hit or null if it fired when moving off an entity
示例
1 system.initialize = function() {
2 	this.listenForEvent("minecraft:pick_hit_result_changed", (eventData) => this.onPick(eventData)); 
3 };
1 system.onPick = function(eventData) { 
2 	if (eventData.position !== null) { 
3 		this.broadcastEvent("minecraft:display_chat_event", "Pick at x:" + eventData.position.x + " y:" + eventData.position.y + " z:" + eventData.position.z); 
4 	} 
5 };
minecraft:pick_hit_result_continuous[]

This event is triggered every update and tells you what entity the mouse pointer is pointing to in the world up to 1000 blocks away.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The entity that was hit or null if it not pointing at an entity
数组(Vector)[a, b, c] position The position of the entity that was hit or block that was hit
示例
1 system.initialize = function() {
2 	this.listenForEvent("minecraft:pick_hit_result_continuous", (eventData) => this.onPick(eventData)); 
3 };
1 system.onPick = function(eventData) { 
2 	if (eventData.position !== null) { 
3 		this.broadcastEvent("minecraft:display_chat_event", "Pick at x:" + eventData.position.x + " y:" + eventData.position.y + " z:" + eventData.position.z); 
4 	} 
5 };

Triggerable events[]

The following Minecraft Events can be triggered from scripting and cause the game to respond accordingly.

minecraft:display_chat_event[]

This event is used to display a chat message to the specific player that is running the client script. The event data is the message to be displayed in plain text. Special formatting is supported the same way it would be if a player was sending the message.

参数[]
类型 名称 默认值 描述
字符串(String) message The chat message to be displayed


minecraft:load_ui[]

This event is used to show a UI screen to the specific player running the client script. This event adds the UI screen to the top of the UI screen stack. The screen is shown immediately after the event is triggered. Only screens defined in a HTML file can be shown using this event.

Event Data 参数
类型 名称 默认值 描述
字符串(String) path The file path to the screen's HTML file
JSON 对象(JSON Object) options You can define the following options for the screen by setting their value to true or false:

always_accepts_input

If true, the screen always accepts and processes input for as long as it is in the stack, even if other custom UI screens appear on top of it

render_game_behind

If true, the game continues to be rendered underneath this screen

absorbs_input

If true, input does pass down to any other screens underneath

is_showing_menu

If true, the screen is treated as the pause menu and the pause menu won't be allowed to show on top of this screen

should_steal_mouse

If true, the screen captures the mouse pointer and limits its movement to the UI screen

force_render_below

If true, this screen is rendered even if another screen is on top of it and renders over them, including the HUD

render_only_when_topmost

If true, this screen is rendered only if it is the screen at the top of the stack

minecraft:send_ui_event[]

This event is used to send UI events to the UI Engine for the specific player running the script. After the event is triggered, the UI event is sent immediately. Custom UI is based on HTML 5. Review the scripting demo for an example of a custom UI file.

参数[]
类型 名称 描述
字符串(String) eventIdentifier The identifier of the UI event
字符串(String) data The data for the UI event being triggered
minecraft:spawn_particle_attached_entity[]

This event is used to create a particle effect that follows an entity around. This particle effect is only visible to the specific player that is running the client script where you fired the event. Any effect defined in a JSON file (both in your resource pack and in Minecraft) can be used here. MoLang variables defined in the JSON of the effect can then be used to control that effect by changing them in the entity to which it is attached.

参数[]
类型 名称 默认值 描述
字符串(String) effect The identifier of the particle effect you want to attach to the entity. This is the same name you gave the effect in its JSON file
数组(Vector)[a, b, c] offset [0, 0, 0] The offset from the entity's "center" where you want to spawn the effect
实体 JS API 对象(Entity JS API object) entity The entity object you want to attach the effect to
minecraft:spawn_particle_in_world[]

This event is used to create a static particle effect in the world. This particle effect is only visible to the specific player that is running the client script where you fired the event. Any effect defined in a JSON file (both in your resource pack and in Minecraft) can be used here. Once the effect is spawned you won't be able to control it further. Unlike the server version of the event, the client version spawns the particle in the dimension the player is currently in.

参数[]
类型 名称 默认值 描述
字符串(String) effect The identifier of the particle effect you want to attach to spawn. This is the same name you gave the effect in its JSON file
数组(Vector)[a, b, c] position [0, 0, 0] The position in the world where you want to spawn the effect
minecraft:unload_ui[]

This event is used to remove a UI screen from the stack of the specific player running the client script. The event data contains the name of the screen to remove as a string. After the event is triggered, the screen is scheduled to be removed from the stack the next time the UI Engine can do so. Only screens defined in a HTML file can be removed using this event.

minecraft:script_logger_config[]

This event is used to turn various levels of logging on and off for client scripts. Note that turning logging on/off is not limited to the script that broadcasted the event. It affects all client scripts including those in other Behavior Packs that are applied to the world. See the Debugging section for more information on logging.

参数[]
类型 名称 默认值 描述
布尔值(Boolean) log_errors false Set to true to log any scripting errors that occur on the client
布尔值(Boolean) log_warnings false Set to true to log any scripting warnings that occur on the client
布尔值(Boolean) log_information false Set to true to log any general scripting information that occurs on the client. This includes any logging done with client.log()

服务器事件(Server events)[]

Listening events[]

The following Minecraft events are events the Script Engine is listening for and to which you can react in scripts.

minecraft:player_attacked_entity[]

This event is triggered whenever a player attacks an entity.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) player The player that attacked an entity
实体 JS API 对象(Entity JS API object) attacked_entity The entity that was attacked by the player
minecraft:entity_acquired_item[]

This event is triggered whenever an entity acquires an item.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The entity who acquired the item
堆叠物品JS API对象(ItemStack JS API object) item_stack The item that was acquired
字符串(String) acquisition_method The way the entity acquired the item
整数(Integer) acquired_amount The total number of items acquired by the entity during this event
实体 JS API 对象(Entity JS API object) secondary_entity If it exists, the entity that affected the item before it was acquired. Example: A player completes a trade with a villager. The `entity` property would be the player and the `secondary_entity` would be the villager
minecraft:entity_carried_item_changed[]

This event is triggered whenever an entity changes the item carried in their hand.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The entity that changed what they were carrying
堆叠物品JS API对象(ItemStack JS API object) previous_carried_item The item that was previously in the entities hands
堆叠物品JS API对象(ItemStack JS API object) carried_item The item that is now in the entities hands
minecraft:entity_created[]

This event is triggered whenever an entity is added to the world.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The entity that was just created
minecraft:entity_death[]

This event is triggered whenever an entity dies. This won't be triggered when an entity is removed (such as when using destroyEntity).

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The entity that died
minecraft:entity_dropped_item[]

This event is triggered whenever an entity drops an item.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The entity who dropped the item
堆叠物品JS API对象(ItemStack JS API object) item_stack The item that was dropped
minecraft:entity_equipped_armor[]

This event is triggered whenever an entity equips an item in their armor slots.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The entity who is equipping the armor
堆叠物品JS API对象(ItemStack JS API object) item_stack The armor that is being equipped
minecraft:entity_start_riding[]

This event is triggered whenever an entity becomes a rider on another entity.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The rider
实体 JS API 对象(Entity JS API object) ride The entity being ridden
minecraft:entity_stop_riding[]

This event is triggered whenever an entity stops riding another entity.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The entity that was riding another entity
布尔值(Boolean) exit_from_rider If true, the rider stopped riding by their own decision
布尔值(Boolean) entity_is_being_destroyed If true, the rider stopped riding because they are now dead
布尔值(Boolean) switching_rides If true, the rider stopped riding because they are now riding a different entity
minecraft:entity_tick[]

This event is triggered whenever an entity is ticked. This event does not fire when a player is ticked.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The entity that was ticked
minecraft:entity_use_item[]

This event is triggered whenever an entity uses an item.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) entity The entity who is using the item
堆叠物品JS API对象(ItemStack JS API object) item_stack The item that is being used
字符串(String) use_method The way the entity used the item
minecraft:block_destruction_started[]

This event is triggered whenever a player starts to destroy a block.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) player The player that started destoying the block
JavaScript 对象(JavaScript object) block_position The position of the block that is being destroyed
minecraft:block_destruction_stopped[]

This event is triggered whenever a player stops destroying a block.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) player The player that stopped destoying the block
JavaScript 对象(JavaScript object) block_position The position of the block that was being destroyed
Decimal destruction_progress How far along the destruction was before it was stopped (0 - 1 range)
minecraft:block_interacted_with[]

This event is triggered whenever a player interacts with a block.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) player The player that interacted with the block
JavaScript 对象(JavaScript object) block_position The position of the block that is being interacted with
minecraft:piston_moved_block[]

This event is triggered whenever a piston moves a block.

参数[]
类型 名称 描述
JavaScript 对象(JavaScript object) piston_position The position of the piston that moved the block
JavaScript 对象(JavaScript object) block_position The position of the block that was moved
字符串(String) piston_action The action the piston took, "extended" or "retracted"
minecraft:player_destroyed_block[]

This event is triggered whenever a player destroys a block.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) player The player that destroyed the block
JavaScript 对象(JavaScript object) block_position The position of the block that was destroyed
字符串(String) block_identifier The identifier of the block that was destroyed
minecraft:player_placed_block[]

This event is triggered whenever a player places a block.

参数[]
类型 名称 描述
实体 JS API 对象(Entity JS API object) player The player that placed the block
JavaScript 对象(JavaScript object) block_position The position of the block that was placed
minecraft:play_sound[]

This event is used to play a sound effect. Currently, sounds can only be played at a fixed position in the world. Global sounds and sounds played by an entity may be supported in a later update.

参数[]
类型 名称 默认值 描述
字符串(String) sound The identifier of the sound you want to play. Only sounds defined in the applied resource packs can be played
Decimal volume 1.0 The volume of the sound effect. A value of 1.0 plays the sound effect at the volume it was recorded at
Decimal pitch 1.0 The pitch of the sound effect. A value of 1.0 plays the sound effect with regular pitch
数组(Vector)[a, b, c] position [0, 0, 0] The position in the world we want to play the sound at
minecraft:weather_changed[]

This event is triggered whenever the weather changes. It contains information about the weather it is changing to.

参数[]
类型 名称 描述
字符串(String) dimension The name of the dimension where the weather change happened
布尔值(Boolean) raining Tells if the new weather has rain
布尔值(Boolean) lightning Tells if the new weather has lightning

可触发的事件[]

以下Minecraft事件可以在脚本中触发并获得相应的回应消息.

minecraft:display_chat_event[]

此事件可以从服务端发送给玩家一段聊天信息. 这个事件的数据以字符串的形式发送出去. 它支持特殊格式, 就像一个玩家想要发送消息一样.

参数[]
类型 名称 默认值 描述
字符串(String) message 显示的聊天消息
minecraft:execute_command[]

此事件用于在服务端上执行一个世界拥有者等级的斜杠(/)命令(比如/op)。参数包含一个字符串格式的命令。命令在数据发送出去之后才会执行。

参数[]
类型 名称 默认值 描述
字符串(String) command 需要运行的命令
minecraft:play_sound[]

此事件用来播放一个音效。目前,音效只能在固定的世界坐标上播放。在以后的版本中可能会支持全局音效和实体播放音效。

参数[]
类型 名称 默认值 描述
字符串(String) sound 你想要播放的音效的标识符。只能播放在已加载的资源包中定义的音效。
精确小数(Decimal) volume 1.0 你所播放的音效的音量。当值为1.0时会播放和录制时相同的音量。
精确小数(Decimal) pitch 1.0 音效的音调。当值为1.0时音效为标准音调。
数组(Vector)[a, b, c] position [0, 0, 0] 播放音效的坐标
minecraft:spawn_particle_attached_entity[]

This event is used to create a particle effect that follows an entity around. This particle effect is visible to all players. Any effect defined in a JSON file (both in your resource pack and in Minecraft) can be used here. MoLang variables defined in the JSON of the effect can then be used to control that effect by changing them in the entity to which it is attached.

参数[]
类型 名称 默认值 描述
字符串(String) effect The identifier of the particle effect you want to attach to the entity. This is the same identifier you gave the effect in its JSON file
数组(Vector)[a, b, c] offset [0, 0, 0] The offset from the entity's "center" where you want to spawn the effect
实体 JS API 对象(Entity JS API object) entity The entity object you want to attach the effect to
minecraft:spawn_particle_in_world[]

This event is used to create a static particle effect in the world. This particle effect is visible to all players. Any effect defined in a JSON file (both in your resource pack and in Minecraft) can be used here. Once the effect is spawned you won't be able to control it further.

参数[]
类型 名称 默认值 描述
字符串(String) effect The identifier of the particle effect you want to attach to spawn. This is the same name you gave the effect in its JSON file
数组(Vector)[a, b, c] position [0, 0, 0] The position in the world where you want to spawn the effect
字符串(String) dimension overworld The dimension in which you want to spawn the effect. Can be "overworld", "nether", or "the end"
minecraft:script_logger_config[]

This event is used to turn various levels of logging on and off for server scripts. Note that turning logging on/off is not limited to the script that broadcasted the event. It affects all server scripts including those in other Behavior Packs that are applied to the world. See the Debugging section for more information on logging.

参数[]
类型 名称 默认值 描述
布尔值(Boolean) log_errors false Set to true to log any scripting errors that occur on the server
布尔值(Boolean) log_warnings false Set to true to log any scripting warnings that occur on the server
布尔值(Boolean) log_information false Set to true to log any general scripting information that occurs on the server. This includes any logging done with server.log()

参见[]

Advertisement