For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /server/classes/World.md.

Class: World

world

Beta

表示一个世界。包含了世界的各种状态,即一系列维度以及 Minecraft 的环境。

A class that wraps the state of a world - a set of dimensions and the environment of Minecraft.

Properties

afterEvents

readonly afterEvents: WorldAfterEvents

Early Execution Beta

Remarks

包含适用于整个世界的一组事件。事件回调以延迟方式调用,且以读写模式执行。

Contains a set of events that are applicable to the entirety of the world. Event callbacks are called in a deferred manner. Event callbacks are executed in read-write mode.


allowCheats

实验性

allowCheats: boolean

Beta World Mutation

Remarks

启用或禁用作弊功能。

Enables or disables cheats.


beforeEvents

readonly beforeEvents: WorldBeforeEvents

Early Execution Beta

Remarks

Tip

包含适用于整个世界的一组事件。事件回调以立即方式调用,且以只读模式执行。

Tip

Contains a set of events that are applicable to the entirety of the world. Event callbacks are called immediately. Event callbacks are executed in read-only mode.

Example

customCommand.ts

import { world, DimensionLocation } from '@minecraft/server';

function customCommand(targetLocation: DimensionLocation) {
  const chatCallback = world.beforeEvents.chatSend.subscribe(eventData => {
    if (eventData.message.includes('cancel')) {
      // Cancel event if the message contains "cancel"
      eventData.cancel = true;
    } else {
      const args = eventData.message.split(' ');

      if (args.length > 0) {
        switch (args[0].toLowerCase()) {
          case 'echo':
            // Send a modified version of chat message
            world.sendMessage(`Echo '${eventData.message.substring(4).trim()}'`);
            break;
          case 'help':
            world.sendMessage(`Available commands: echo <message>`);
            break;
        }
      }
    }
  });
}

gameRules

readonly gameRules: GameRules

Beta

Remarks

适用于该世界的游戏规则。

The game rules that apply to the world.


isHardcore

readonly isHardcore: boolean

Beta


primitiveShapesManager

readonly primitiveShapesManager: PrimitiveShapesManager

Beta

Remarks

用于在世界中添加和移除原始文本对象的管理器。

Manager for adding and removing primitive text objects in the world.


scoreboard

readonly scoreboard: Scoreboard

Beta

Remarks

全局的、唯一的记分板对象。

Returns the general global scoreboard that applies to the world.


seed

readonly seed: string

Beta

Remarks

世界的种子。

The world seed.


soundDefinitionRegistry

实验性

readonly soundDefinitionRegistry: SoundDefinitionRegistry

Beta

Remarks

提供对当前世界已加载的声音定义的只读访问。

Provides read-only access to the sound definitions loaded for this world.


structureManager

readonly structureManager: StructureManager

Beta

Remarks

返回与 Structure 相关 API 的管理器。

Returns the manager for Structure related APIs.


tickingAreaManager

readonly tickingAreaManager: TickingAreaManager

Beta

Remarks

用于添加、移除和查询资源包专用的常加载区域的管理器。

Manager for adding, removing and querying pack specific ticking areas.

Methods

broadcastClientMessage()

broadcastClientMessage(id, value): void

Beta World Mutation

Parameters

id

string

消息的标识符。

The message identifier.

value

string

消息内容。

The message.

Returns

void

Remarks

一个仅供内部使用的方法,用于在客户端与服务端之间广播特定消息。

A method that is internal-only, used for broadcasting specific messages between client and server.


clearDynamicProperties()

clearDynamicProperties(): void

Beta

Returns

void

Remarks

清除该行为包在世界中所声明的一组动态属性。

Clears the set of dynamic properties declared for this behavior pack within the world.


getAbsoluteTime()

getAbsoluteTime(): number

Beta

Returns

number

自游戏开始以来流逝的时间,以刻为单位。

Remarks

获取自游戏开始以来流逝的时间(计算公式:day*24000+daytime)。 时间的流逝受到游戏规则 dodaylightcycle 的影响。

Returns the absolute time since the start of the world.


getAimAssist()

getAimAssist(): AimAssistRegistry

Beta

Returns

AimAssistRegistry

Remarks

该世界中可用的瞄准辅助预设与类别。

The aim-assist presets and categories that can be used in the world.


getAllPlayers()

getAllPlayers(): Player[]

Beta

Returns

Player[]

返回包含了游戏中所有玩家的对象的数组。

Remarks

获取一个包含了游戏中所有玩家的对象的数组。

Returns an array of all active players within the world.

Throws

This function can throw errors.

CommandError

InvalidArgumentError


getDay()

getDay(): number

Beta

Returns

number

当前天数,由世界时间除以每天的刻数得出。新世界的天数为 0。

The current day, determined by the world time divided by the number of ticks per day. New worlds start at day 0.

Remarks

返回当前天数。

Returns the current day.


getDefaultSpawnLocation()

getDefaultSpawnLocation(): Vector3

Beta

Returns

Vector3

主世界默认的出生点位置。默认情况下 Y 坐标为 32767,表示玩家出生高度不固定,将由周围方块决定。

The default Overworld spawn location. By default, the Y coordinate is 32767, indicating a player's spawn height is not fixed and will be determined by surrounding blocks.

Remarks

返回主世界默认的出生点位置。

Returns the default Overworld spawn location.


getDifficulty()

getDifficulty(): Difficulty

Beta

Returns

Difficulty

返回世界难度。

Returns the world difficulty.

Remarks

从世界中获取难度。

Gets the difficulty from the world.


getDimension()

getDimension(dimensionId): Dimension

Beta

Parameters

dimensionId

string

要获取的维度的标识符。

The name of the dimension. For example, "overworld", "nether" or "the_end".

Returns

Dimension

dimensionId 关联的维度对象。

The requested dimension

Remarks

dimensionId 获取维度对象。

Returns a dimension object.

Throws

dimensionId 不与任何维度关联,抛出 "Dimension '<dimensionId>' is invalid"

Throws if the given dimension name is invalid


getDynamicProperty()

getDynamicProperty(identifier): string | number | boolean | Vector3 | undefined

Beta

Parameters

identifier

string

动态属性的标识符。

The property identifier.

Returns

string | number | boolean | Vector3 | undefined

返回动态属性 identifier 的值。属性的值尚未设定时,返回 undefined

Returns the value for the property, or undefined if the property has not been set.

Remarks

获取由 identifier 指定的世界中已定义的动态属性的值。

Returns a property value.

Throws

若并未注册以 identifier 为标识符的动态属性,抛出 "Dynamic Property '<identifier>' is not defined"

Throws if the given dynamic property identifier is not defined.

Examples

incrementDynamicProperty.ts

import { world, DimensionLocation } from '@minecraft/server';

function incrementDynamicProperty(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
  let number = world.getDynamicProperty('samplelibrary:number');

  log('Current value is: ' + number);

  if (number === undefined) {
    number = 0;
  }

  if (typeof number !== 'number') {
    log('Number is of an unexpected type.');
    return -1;
  }

  world.setDynamicProperty('samplelibrary:number', number + 1);
}

incrementDynamicPropertyInJsonBlob.ts

import { world, DimensionLocation } from '@minecraft/server';

function incrementDynamicPropertyInJsonBlob(
  log: (message: string, status?: number) => void,
  targetLocation: DimensionLocation
) {
  let paintStr = world.getDynamicProperty('samplelibrary:longerjson');
  let paint: { color: string; intensity: number } | undefined = undefined;

  log('Current value is: ' + paintStr);

  if (paintStr === undefined) {
    paint = {
      color: 'purple',
      intensity: 0,
    };
  } else {
    if (typeof paintStr !== 'string') {
      log('Paint is of an unexpected type.');
      return -1;
    }

    try {
      paint = JSON.parse(paintStr);
    } catch (e) {
      log('Error parsing serialized struct.');
      return -1;
    }
  }

  if (!paint) {
    log('Error parsing serialized struct.');
    return -1;
  }

  paint.intensity++;
  paintStr = JSON.stringify(paint); // be very careful to ensure your serialized JSON str cannot exceed limits
  world.setDynamicProperty('samplelibrary:longerjson', paintStr);
}

getDynamicPropertyIds()

getDynamicPropertyIds(): string[]

Beta

Returns

string[]

处于活跃状态的动态属性标识符的字符串数组。

A string array of active dynamic property identifiers.

Remarks

获取在世界中已设置的动态属性标识符集合。

Gets a set of dynamic property identifiers that have been set in this world.


getDynamicPropertyTotalByteCount()

getDynamicPropertyTotalByteCount(): number

Beta

Returns

number

Remarks

获取动态属性的总字节数。可用于自行分析,确保不会存储过大的动态属性集合。

Gets the total byte count of dynamic properties. This could potentially be used for your own analytics to ensure you're not storing gigantic sets of dynamic properties.


getEntity()

getEntity(id): Entity | undefined

Beta

Parameters

id

string

实体的 id。

The id of the entity.

Returns

Entity | undefined

所请求的实体对象。

The requested entity object.

Remarks

根据提供的 id 获取实体。

Returns an entity based on the provided id.

Throws

若提供的实体 id 无效,则抛出错误。

Throws if the given entity id is invalid.


getLootTableManager()

getLootTableManager(): LootTableManager

Beta

Returns

LootTableManager

一个包含多种战利品生成方法的战利品表管理器。

A loot table manager with a variety of loot generation methods.

Remarks

返回一个可从各种来源生成战利品的管理器。

Returns a manager capable of generating loot from an assortment of sources.


getMoonPhase()

getMoonPhase(): MoonPhase

Beta

Returns

MoonPhase

Remarks

返回当前时间的月相(MoonPhase)。

Returns the MoonPhase for the current time.


getPackSettings()

getPackSettings(): Record<string, boolean | number | string>

Early Execution Beta

Returns

Record<string, boolean | number | string>

Remarks

返回由资源包设置项的名称和值构成的映射。

Returns a map of pack setting name and value pairs.


getPlayers()

getPlayers(options?): Player[]

Beta

Parameters

options?

EntityQueryOptions

可选的参数,用作于筛选指定条件的玩家。

注意,不能使用接口中的 typelocationmaxDistanceminDistancevolume 属性。

Additional options that can be used to filter the set of players returned.

Returns

Player[]

A player array.

Remarks

列出世界上的玩家,可使用 options 指定的实体查询选项对其进行筛选。

Returns a set of players based on a set of conditions defined via the EntityQueryOptions set of filter criteria.

Throws

若向 options 传入的对象含有 type 属性,抛出 "command.generic.invalidPlayerType"

若向 options 传入的对象含有 locationmaxDistanceminDistancevolume 属性,抛出 "EntityQueryOptions property '<property>' is incompatible with function world.getPlayers"

Throws if the provided EntityQueryOptions are invalid.

CommandError

InvalidArgumentError


getTimeOfDay()

getTimeOfDay(): number

Beta

Returns

number

当前一天中的时间,以刻为单位,为 024000 之间的整数。

The time of day, in ticks, between 0 and 24000.

Remarks

返回当前一天中的时间。

Returns the time of day.


playMusic()

playMusic(trackId, musicOptions?): void

World Mutation Beta

Parameters

trackId

string

声音项目的标识符,要求声音项目的类别为音乐(category: music)。

musicOptions?

MusicOptions

可选,指定播放音乐使用的附加参数。

Returns

void

Remarks

停止正在播放的音乐,并开始向玩家播放指定音乐。播放类别不为音乐的声音项目不会有任何效果。

Plays a particular music track for all players.

Throws

This function can throw errors.

PropertyOutOfBoundsError

Example

playMusicAndSound.ts

import { world, MusicOptions, WorldSoundOptions, PlayerSoundOptions, DimensionLocation } from '@minecraft/server';

function playMusicAndSound(targetLocation: DimensionLocation) {
  const players = world.getPlayers();

  const musicOptions: MusicOptions = {
    fade: 0.5,
    loop: true,
    volume: 1.0,
  };
  world.playMusic('music.menu', musicOptions);

  const worldSoundOptions: WorldSoundOptions = {
    pitch: 0.5,
    volume: 4.0,
  };
  world.playSound('ambient.weather.thunder', targetLocation, worldSoundOptions);

  const playerSoundOptions: PlayerSoundOptions = {
    pitch: 1.0,
    volume: 1.0,
  };

  players[0].playSound('bucket.fill_water', playerSoundOptions);
}

queueMusic()

queueMusic(trackId, musicOptions?): void

World Mutation Beta

Parameters

trackId

string

声音项目的标识符,要求声音项目的类别为音乐(category: music)。

Identifier of the music track to play.

musicOptions?

MusicOptions

可选,指定播放音乐使用的附加参数。

Additional options for the music track.

Returns

void

Remarks

将音乐添加到播放列表。如果没有任何正在播放的音乐,将会开始播放音乐。播放列表中的音乐将会按照添加顺序播放(需要更多测试)。

Queues an additional music track for players. If a track is not playing, a music track will play.

Throws

An error will be thrown if volume is less than 0.0. An error will be thrown if fade is less than 0.0.

PropertyOutOfBoundsError


sendMessage()

sendMessage(message): void

Beta

Parameters

message

string | RawMessage | (string | RawMessage)[]

将要广播的一段消息。 这段消息可能是一段字符串,或者符合 RawMessage 接口的对象,或是这两种类型的组合。

The message to be displayed.

Returns

void

Remarks

向所有玩家广播一条消息。

Sends a message to all players.

Throws

该方法在 message 格式不正确时会抛出错误。例如 scorename 为空字符串时。

This method can throw if the provided RawMessage is in an invalid format. For example, if an empty name string is provided to score.


setAbsoluteTime()

setAbsoluteTime(absoluteTime): void

World Mutation Beta

Parameters

absoluteTime

number

世界时间,以刻为单位。

The world time, in ticks.

Returns

void

Remarks

设置世界时间。

Sets the world time.


setDefaultSpawnLocation()

setDefaultSpawnLocation(spawnLocation): void

World Mutation Beta

Parameters

spawnLocation

Vector3

出生点的位置。注意假定其位于主世界(overworld)中。

Location of the spawn point. Note that this is assumed to be within the overworld dimension.

Returns

void

Remarks

为所有玩家设置一个默认出生点位置。

Sets a default spawn location for all players.

Throws

若提供的出生点位置超出世界边界,则抛出错误。

Throws if the provided spawn location is out of bounds.

Error

LocationOutOfWorldBoundariesError


setDifficulty()

setDifficulty(difficulty): void

World Mutation Beta

Parameters

difficulty

Difficulty

想要设置的世界难度。

The difficulty we want to set the world to.

Returns

void

Remarks

设置世界难度。

Sets the worlds difficulty.


setDynamicProperties()

setDynamicProperties(values): void

Beta

Parameters

values

Record<string, boolean | number | string | Vector3 | undefined>

由键值对组成的记录,每个条目对应一个动态属性。若数据值为 null,则会移除该属性。

A Record of key value pairs of the dynamic properties to set. If the data value is null, it will remove that property instead.

Returns

void

Remarks

同时设置多个动态属性为指定值。

Sets multiple dynamic properties with specific values.

Throws

This function can throw errors.

ArgumentOutOfBoundsError


setDynamicProperty()

setDynamicProperty(identifier, value?): void

Beta

Parameters

identifier

string

动态属性的标识符。

The property identifier.

value?

string | number | boolean | Vector3

要设定的值,值的类型必须与动态属性注册的类型相同。若值为 null,该属性将被移除。

Data value of the property to set. If the value is null, it will remove the property instead.

Returns

void

Remarks

为世界动态属性 identifier 设置一个值。

Sets a specified property to a value.

Throws

若并未注册以 identifier 为标识符的动态属性,抛出 "Dynamic Property '<identifier>' is not defined"

若动态属性的类型不符合值的类型,抛出 "Type mismatch for dynamic property '<identifier>'"

若动态属性的类型为字符串,且值在使用 UTF-8 编码后的字节长度大于动态属性所允许的最大长度,抛出 "Maximum string length exceeded (<length>/<maxLength>) for dynamic property '<identifier>'"

Throws if the given dynamic property identifier is not defined.

ArgumentOutOfBoundsError

Examples

incrementDynamicProperty.ts

import { world, DimensionLocation } from '@minecraft/server';

function incrementDynamicProperty(log: (message: string, status?: number) => void, targetLocation: DimensionLocation) {
  let number = world.getDynamicProperty('samplelibrary:number');

  log('Current value is: ' + number);

  if (number === undefined) {
    number = 0;
  }

  if (typeof number !== 'number') {
    log('Number is of an unexpected type.');
    return -1;
  }

  world.setDynamicProperty('samplelibrary:number', number + 1);
}

incrementDynamicPropertyInJsonBlob.ts

import { world, DimensionLocation } from '@minecraft/server';

function incrementDynamicPropertyInJsonBlob(
  log: (message: string, status?: number) => void,
  targetLocation: DimensionLocation
) {
  let paintStr = world.getDynamicProperty('samplelibrary:longerjson');
  let paint: { color: string; intensity: number } | undefined = undefined;

  log('Current value is: ' + paintStr);

  if (paintStr === undefined) {
    paint = {
      color: 'purple',
      intensity: 0,
    };
  } else {
    if (typeof paintStr !== 'string') {
      log('Paint is of an unexpected type.');
      return -1;
    }

    try {
      paint = JSON.parse(paintStr);
    } catch (e) {
      log('Error parsing serialized struct.');
      return -1;
    }
  }

  if (!paint) {
    log('Error parsing serialized struct.');
    return -1;
  }

  paint.intensity++;
  paintStr = JSON.stringify(paint); // be very careful to ensure your serialized JSON str cannot exceed limits
  world.setDynamicProperty('samplelibrary:longerjson', paintStr);
}

setTimeOfDay()

setTimeOfDay(timeOfDay): void

World Mutation Beta

Parameters

timeOfDay

number

一天内的时间,以刻为单位,介于 0 至 24000 之间。

The time of day, in ticks, between 0 and 24000.

Returns

void

Remarks

设置一天内的时间。

Sets the time of day.

Throws

若提供的一天内的时间不在有效范围内,则抛出错误。

Throws if the provided time of day is not within the valid range.


stopMusic()

stopMusic(): void

World Mutation Beta

Returns

void

Remarks

停止客户端中正在播放的所有音乐曲目(需要更多测试)。

Stops any music tracks from playing.

同领域相关