> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/lian-wang/serverless-multiplayer.md).

# 无服务器多人模式

在玩家之间同步场景状态。

Decentraland 会在玩家的 Explorer 实例中本地运行场景。默认情况下，玩家可以看到彼此并直接互动，但每位玩家都是独立地与环境互动。默认情况下，环境中的变化不会在玩家之间共享。

让玩家看到处于相同状态的相同内容，对于玩家以更有意义的方式互动至关重要。

有三种方法可以同步场景状态，让所有玩家看到相同的内容：

* **将实体标记为已同步**：最简单的选项。请参阅 [将实体标记为已同步](#mark-an-entity-as-synced)
* **发送显式 MessageBus 消息**：手动发送并监听特定消息。请参阅 [发送显式 MessageBus 消息](#send-explicit-messagebus-messages)
* **使用多人游戏服务器**：请参阅 [多人游戏服务器](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/lian-wang/authoritative-servers.md)。服务器会验证所有状态更改，并作为唯一可信数据源。虽然需要进行更多设置，但如果玩家有动机利用场景漏洞，我们强烈建议采用此方案。

本文档介绍前两种方案。它们更简单，因为不需要服务器。缺点是你会更依赖玩家的网络连接速度，而且所有玩家离开场景后，场景状态不会保留。

## 将实体标记为同步

在 [Creator Hub](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/ru-men/about-editor.md)中，为实体添加 **多人游戏组件** ，即可将其标记为同步。该组件会为实体上的其他每个组件提供一个复选框，让你选择要更新哪些组件。

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-3c4e9da9a4f012190b0cfd80e26ad80580ab9ba7%2Fmultiplayer-component.webp?alt=media)

要通过代码将实体标记为已同步，请使用 `syncEntity` 函数：

```ts
import { syncEntity } from "@dcl/sdk/network";

export function main() {
  const doorEntity = engine.addEntity();

  syncEntity(doorEntity, [Transform.componentId, Animator.componentId], 1);
}
```

{% hint style="warning" %}
**📔 注意**：始终在 `syncEntity()` 内部调用 `main()` 函数，或在运行于……之后的函数中 `main()` （例如回调或系统）。在文件顶层调用它会引发错误，因为此时玩家资料尚未初始化。
{% endhint %}

{% hint style="warning" %}
**📔 注意**：在无服务器多人游戏中，每个客户端都会自行调用 `syncEntity` 。如果升级到 [多人游戏服务器](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/lian-wang/authoritative-servers.md)，调用模式会发生变化：只有服务器才应调用 `syncEntity`，并通过……进行保护 `isServer()`。客户端应避免声明同步共享实体，除非这些实体由该客户端创建。
{% endhint %}

此 `syncEntity` 函数接受以下输入：

* **entityId**：要同步的实体的引用
* **componentIds**：需要从该实体同步的组件列表。这是一个数组，可包含任意数量的组件。所有值都应为 `componentId` 属性。
* **entityEnumId**： （可选）所有玩家都一致使用的唯一 ID，请参阅 [关于枚举 ID](#about-the-enum-id).

并非所有实体或组件都需要同步。树木这类始终留在原地的静态元素无需同步。对于需要同步的实体，只应同步会随时间变化的组件。例如，如果一个立方体会在单击后改变颜色，则只需同步 Material 组件，而不需要同步 MeshRenderer 或 Transform，因为它们不会改变。

{% hint style="info" %}
**💡 提示**：如果要共享的数据并不存在于组件中，请定义一个 [自定义组件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/custom-components.md) 来存储这些数据。
{% endhint %}

### 关于枚举 ID

实体的 **entityEnumId** 必须是唯一的。它与在 `engine.addEntity()`上分配的本地 entityId 无关；后者会自动生成，并且在运行同一场景的不同玩家之间可能有所不同。实体的 entityEnumId 必须在代码中显式定义，并且必须唯一。

显式设置此 ID 很重要，这样可以避免竞态条件导致场景的一部分先于另一部分加载时出现不一致。例如，对玩家 A 来说，场景中的门是实体 *512*，但对玩家 B 来说，同一扇门却是实体 *513*。在这种情况下，如果玩家 A 打开门，玩家 B 看到的就会是整栋建筑在移动。

{% hint style="info" %}
**💡 提示**：在场景中创建一个枚举，以便清楚地引用场景中每个可同步 ID。

```ts
import { syncEntity } from "@dcl/sdk/network";

enum EntityEnumId {
  DOOR = 1,
  DRAW_BRIDGE = 2,
  ELEVATOR = 3,
}

export function main() {
  syncEntity(
    doorEntity,
    [Transform.componentId, Animator.componentId],
    EntityEnumId.DOOR
  );
}
```

此处使用 EntityEnumId 枚举为实体标记唯一标识符，确保每个客户端都能识别被修改的实体，无论实体的创建顺序如何。
{% endhint %}

{% hint style="warning" %}
**📔 注意**：如果场景中还包含 Smart Items，请避免使用大于 **8001** 的数字。通过 [Creator Hub](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/ru-men/about-editor.md) 创建且带有 Multiplayer 组件的项目会从 8001 开始使用自动分配的 ID。任何小于 8001 的 ID 都可以安全地分配给需要同步的实体。
{% endhint %}

**由玩家创建的实体**

如果某个实体是由玩家交互创建的，并且需要与其他玩家同步，则该实体不需要 entityEnumId。你可以调用 `syncEntity()` ，只传入实体和组件列表。系统会在后台自动为 entityEnumId 分配唯一值。

场景启动时实例化的所有实体都必须手动分配 ID，以确保所有玩家为每个实体使用相同的 ID。当由单个玩家负责实例化实体时，则不需要显式指定 ID。其他玩家会收到有关这个新实体的更新，其中已包含分配好的 ID，因此不会出现 ID 不匹配的风险。

例如，在打雪仗场景中，每当玩家扔出一个雪球时，就会实例化一个与其他玩家同步的新实体。这个雪球不需要唯一的 entityEnumId。

```ts
import { syncEntity } from "@dcl/sdk/network";

function onThrow() {
  const ball = engine.addEntity();
  Transform.create(ball, {});
  GltfContainer.create(ball, { src: "assets/snowBall.glb" });
  syncEntity(ball, [Transform.componentId, GltfContainer.componentId]);
}
```

### 具有父级的实体 <a href="#parented-entities" id="parented-entities"></a>

实体的父级通常通过 `parent` 属性在 `Transform` 组件。不过，此属性指向父级的本地实体 ID，该 ID 可能会变化，详见 [关于枚举 ID](#about-the-enum-id)。对于需要同步的父实体，或包含需要同步的子实体的父实体，请使用 `parentEntity()` 函数，而不要使用 `Transform`.

```ts
import { syncEntity, parentEntity } from "@dcl/sdk/network";

export function main() {
  const parent = engine.addEntity();
  Transform.create(parent, { position: somePosition });
  syncEntity(parent, []);

  const child: Entity = engine.addEntity();
  syncEntity(child, [Transform.componentId]);

  parentEntity(child, parent);
}
```

请注意，父实体和子实体都通过 `syncEntity`进行同步，因此所有玩家对这两个实体使用的 ID 都有一致的认知。即使父实体的组件可能永远不需要更改，这一步也是必需的。在此示例中， `syncEntity` 传入了空的组件数组，以避免同步任何不必要的组件。

{% hint style="warning" %}
**📔 注意**：如果实体既通过 `parentEntity()` 建立了父子关系，又通过 `parent` 属性（位于 `Transform` 组件中）建立了父子关系，则会忽略该 `Transform` 组件中的属性。
{% endhint %}

通过 `parentEntity()` 函数建立实体的父子关系时，还可以使用以下辅助函数：

* **removeParent()**：撤销 `parentEntity()`的效果。调用时只需传入子实体。该实体的新父级将变为场景的根实体。原父实体不会从场景中移除。
* **getParent()**：返回传入实体的父实体。
* **getChildren()**：以可迭代对象的形式返回传入实体的子实体列表。
* **getFirstChild()**：返回传入实体的子实体列表中的第一个子实体。

```ts
import {
  syncEntity,
  parentEntity,
  getParent,
  getFirstChild,
  getChildren,
  removeParent,
} from "@dcl/sdk/network";

export function main() {
  const parent = engine.addEntity();
  Transform.create(parent, { position: somePosition });
  syncEntity(parent, []);

  const child: Entity = engine.addEntity();
  syncEntity(child, [Transform.componentId]);

  // 将 parent 设置为父级
  parentEntity(child, parent);

  // 获取父级
  const getParentResult = getParent(child);
  // 返回父级

  // 获取第一个子级
  const getFirstChildResult = getFirstChild(parent);
  // 返回子级

  // getChildren
  const getChildrenResult = Array.from(getChildren(parent));
  // 返回 [child]

  // 从 child 中移除 parent
  removeParent(child);
}
```

## 检查同步状态

玩家刚加载到场景时，可能还没有与周围的其他玩家同步。如果玩家在同步完成之前就开始更改游戏状态，可能会导致游戏出现问题。我们建议始终先检查玩家是否已完成同步，再允许他们编辑场景中的任何内容。

如果玩家走出场景的地块，那么在他们站在场景外期间，也会与场景不同步。因此，场景系统也必须处理这种情况，因为玩家在附近时，场景仍会继续运行。玩家重新进入场景后，系统会自动根据场景状态所发生的任何变化更新他们。

你可以通过以下 `isStateSyncronized()` 函数检查玩家当前是否已与场景状态同步。此函数会返回一个布尔值；如果玩家已与场景同步，则返回 true。

```ts
import { isStateSyncronized } from "@dcl/sdk/network";

const isConnected = isStateSyncronized();
```

例如，你可以在系统中加入此项检查，并在此函数返回 false 时阻止任何交互。

```ts
import { isStateSyncronized } from "@dcl/sdk/network";

engine.addSystem(() => {
  if (isStateSyncronized() && !button.enabled) {
    console.log("启用开始游戏");
    button.enable();
  }

  if (!isStateSyncronized() && button.enabled) {
    console.log(`禁用开始游戏。`);
    button.disable();
  }
});
```

## 发送显式 MessageBus 消息

{% hint style="warning" %}
**📔 注意**： `MessageBus` API 在 SDK 中已被标记为弃用，并且可能会在未来版本中移除。对于大多数使用场景，建议改用 [将实体标记为已同步](#mark-an-entity-as-synced).
{% endhint %}

**初始化消息总线**

创建一个消息总线对象，以处理玩家之间发送和接收消息所需的方法。

```ts
import { MessageBus } from "@dcl/sdk/message-bus";

const sceneMessageBus = new MessageBus();
```

**发送消息**

使用消息总线的 `.emit` 命令向场景中的所有其他玩家发送消息。

```ts
import { MessageBus } from "@dcl/sdk/message-bus";

const sceneMessageBus = new MessageBus();

const myEntity = engine.addEntity();
MeshRenderer.setBox(myEntity);
MeshCollider.setBox(myEntity);

pointerEventsSystem.onPointerDown(
  {
    entity: myEntity,
    opts: { button: InputAction.IA_PRIMARY, hoverText: "点击" },
  },
  function () {
    sceneMessageBus.emit("box1Clicked", {});
  }
);
```

每条消息都可以将有效负载作为第二个参数。有效负载的类型为 `Object`，其中可以包含你想要发送的任何相关数据。

```ts
import { MessageBus } from "@dcl/sdk/message-bus";

const sceneMessageBus = new MessageBus();

sceneMessageBus.emit("spawn", { position: { x: 10, y: 2, z: 10 } });
```

{% hint style="info" %}
**💡 提示**：如果需要在一条消息中包含多个变量的数据，可以创建自定义类型，将所有数据放在同一个对象中。
{% endhint %}

**接收消息**

要处理场景中所有其他玩家发送的消息，请使用 `.on`。使用此函数时，您需要提供一个消息字符串并定义要执行的函数。每当收到与该字符串匹配的消息时，都会执行一次指定的函数。

```ts
import { MessageBus } from "@dcl/sdk/message-bus";

const sceneMessageBus = new MessageBus();

type NewBoxPosition = {
  position: { x: number; y: number; z: number };
};

sceneMessageBus.on("spawn", (info: NewBoxPosition) => {
  const myEntity = engine.addEntity();
  Transform.create(myEntity, {
    position: { x: info.position.x, y: info.position.y, z: info.position.z },
  });
  MeshRenderer.setBox(myEntity);
  MeshCollider.setBox(myEntity);
});
```

{% hint style="warning" %}
**📔 注意**：玩家发送的消息也会被该玩家自己接收。 `.on` 方法无法区分消息是由该玩家自己发出的，还是由其他玩家发出的。
{% endhint %}

**完整的 MessageBus 示例**

此示例使用消息总线，在每次点击主立方体时发送一条新消息，并在随机位置生成一个新立方体。消息中包含新立方体的位置，因此所有玩家看到的新立方体位置都相同。

```ts
import { MessageBus } from "@dcl/sdk/message-bus";

/// --- Create message bus ---
const sceneMessageBus = new MessageBus();

// Cube factory
function createCube(x: number, y: number, z: number): Entity {
  const meshEntity = engine.addEntity();
  Transform.create(meshEntity, { position: { x, y, z } });
  MeshRenderer.setBox(meshEntity);
  MeshCollider.setBox(meshEntity);

  // When a cube is clicked, send message to spawn another one
  pointerEventsSystem.onPointerDown(
    {
      entity: meshEntity,
      opts: { button: InputAction.IA_PRIMARY, hoverText: "Press E to spawn" },
    },
    function () {
      sceneMessageBus.emit("spawn", {
        position: {
          x: 1 + Math.random() * 8,
          y: Math.random() * 8,
          z: 1 + Math.random() * 8,
        },
      });
    }
  );

  return meshEntity;
}

// Init
createCube(8, 1, 8);

// define type of data
type NewBoxPosition = {
  position: { x: number; y: number; z: number };
};

// on spawn message, create new cube
sceneMessageBus.on("spawn", (info: NewBoxPosition) => {
  createCube(info.position.x, info.position.y, info.position.z);
});
```

## 在本地测试多人游戏场景

启动场景预览，并在两个（或更多）不同的浏览器窗口中打开后，每个打开的窗口都会被视为一名独立玩家，模拟通信服务器会让这些玩家保持同步。

在一个窗口中与场景互动，然后切换到另一个窗口，查看互动效果是否也显示在那里。

使用 Creator Hub，在 **多实例预览** 的 **桌面客户端** 子菜单中打开该选项，然后点击 **播放选项**中的 **播放** 按钮，再打开一个 Decentraland 浏览器窗口。你必须使用不同的地址分别登录两个窗口。重新加载场景时，这些会话仍会保持打开状态。

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-10d53f215e20e8cf603bbf578d0b33df738d058f%2Fpreview-button.webp?alt=media)

或者，你也可以在浏览器地址栏中输入以下内容，打开第二个 Decentraland 浏览器窗口：

> `decentraland://realm=http://127.0.0.1:8000&local-scene=true&debug=true&multi-instance=true`

## 单人场景

如果您的场景部署在 [Decentraland World](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/fa-bu/publishing-options.md#decentraland-worlds)中，您可以将其设为单人场景。玩家彼此不可见，也无法聊天或看到彼此操作所产生的效果。

为此，请配置场景的 `scene.json` 文件，将 **fixedAdapter** 设置为 `offline:offline`。该场景将完全不使用 Communication Service，加入该世界的每位用户也始终都是独自一人。

**示例：**

```json
{
  "worldConfiguration": {
    "name": "my-name.dcl.eth",
    "fixedAdapter": "offline:offline"
  }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/lian-wang/serverless-multiplayer.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
