> 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/3d-nei-rong-ji-chu/shape-components.md). Agents can also search and read this documentation through its [MCP server](https://docs.decentraland.org/~gitbook/mcp).

# 形状组件

了解为实体提供 3D 形状和碰撞的不同组件。

Decentraland 中的三维场景基于 [实体-组件](https://en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80%93system) 模型，场景中的所有内容都是一个 *实体*，每个实体都可以包含 *组件* ，用于定义其特征和功能。

实体渲染出的形状取决于它使用的组件。

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-8bb43741efd4cdb7e001f4dca8acd7f21fbcb48e%2Fecs-simple-components-new.webp?alt=media)

## 在 Creator Hub 中使用场景编辑器

为实体指定形状，最简单的方法是使用场景编辑器。你可以添加一个 **网格渲染器** 组件来提供基本形状，或者添加一个 **GLTF** 组件来引用文件中的 3D 模型。请参阅 [添加组件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/gou-jian/components.md#add-components).

## 基本形状

可以为实体添加几种基本形状，通常称为 *基本体*，方法是为实体添加一个 `MeshRenderer` 组件。

可用的形状如下。某些形状还包含专用于该形状的可选字段。

* **方框**:

  使用 `MeshRenderer.setBox()`，并传入实体。传入 `uvs` 作为额外的可选字段，以映射纹理对齐方式。有关详情，请参阅 [材质](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/materials.md) 。
* **平面**:

  使用 `MeshRenderer.setPlane()`，并传入实体。传入 `uvs` 作为额外的可选字段，以映射纹理对齐方式。有关详情，请参阅 [材质](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/materials.md) 。
* **球体**:

  使用 `MeshRenderer.setSphere()`，并传入实体。
* **圆柱体**:

  使用 `MeshRenderer.setCylinder()`，并传入实体。传入 `radiusTop` 和 `radiusBottom` 作为额外的可选字段，以调整圆柱体。

  提示：设置任一 `radiusTop` 或 `radiusBottom` 设为 0 即可创建圆锥。

以下示例会创建一个立方体：

```ts
const myCube = engine.addEntity()

Transform.create(myCube, {
	position: Vector3.create(8, 1, 8),
})

MeshRenderer.setBox(myCube)
```

以下示例会创建一个圆柱体，并将其 `radiusTop` 设为 0，从而生成一个圆锥：

```ts
const myCone = engine.addEntity()

Transform.create(myCone, {
	position: Vector3.create(8, 1, 8),
})

MeshRenderer.setCylinder(myCone, 1, 0)
```

基本形状不包含材质。若要为其添加颜色或纹理，必须为同一实体指定一个 [材质组件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/materials.md) 。

若要使基本形状可点击，或防止玩家穿过它，必须通过 *碰撞体* 为该实体添加一个 [MeshCollider](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md) 组件。

若要更改已有 `MeshRenderer` 组件的实体形状，请运行 `MeshRenderer.setBox()` 或其他辅助函数，它会覆盖原有形状。无需移除原有组件 `MeshRenderer` ，也无需使用高级语法。

```ts
const myCube = engine.addEntity()

Transform.create(myCube, {
	position: Vector3.create(8, 1, 8),
})

MeshRenderer.setBox(myCube)

// overwrite shape
MeshRenderer.setSphere(myCube)
```

{% hint style="warning" %}
**📔 注意**： `MeshRenderer` 组件必须通过以下语句导入：

> `import { MeshRenderer } from "@dcl/sdk/ecs"`

有关如何轻松处理这些内容，请参阅 [导入](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/ru-men/coding-scenes.md#imports) 。
{% endhint %}

## 3D 模型

对于更复杂的形状，可以使用 Blender 等外部工具创建 3D 模型，然后将其导入为 *.glTF* 或 *.glb* （二进制 *.glTF*). [glTF](https://www.khronos.org/gltf) （GL 传输格式）是 Khronos 推出的开放项目，旨在为 3D 资源提供一种通用且可扩展的格式，同时兼具高效性，并能与现代 Web 技术实现高度互操作。

要将外部模型添加到场景中，请为实体添加一个 `GltfContainer` 组件，并将其 `src` 设为包含该模型的 glTF 文件路径。

```ts
const houseEntity = engine.addEntity()

GltfContainer.create(houseEntity, {
	src: 'models/House.gltf',
})
```

&#x20;`src` 字段是必填项，创建组件时必须为其赋值。在上面的示例中，模型位于场景项目文件夹根目录下的 `models` 文件夹中。

{% hint style="info" %}
**💡 提示**：我们建议将模型单独存放在场景内的 `assets/scene/models` 文件夹中。
{% endhint %}

glTF 模型可以包含自身内嵌的纹理、材质、碰撞体和动画。有关详情，请参阅 [3D 模型](https://github.com/decentraland/docs/blob/main/creator/3d-modeling/3d-models.md) 。要覆盖模型的材质，请使用 [GltfNodeModifiers](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/materials.md#modify-gltf-materials) 组件。详情请参阅 [修改 glTF 材质](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/materials.md#modify-gltf-materials) 。

若要防止玩家穿过 3D 模型，或让模型可以点击，必须为其添加 [碰撞体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md)，它可以内嵌在模型中，也可以通过 `MeshCollider` 组件提供。

请注意，所有模型及其着色器和纹理都必须符合 [场景限制](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/you-hua/scene-limitations.md).

{% hint style="warning" %}
**📔 注意**：必须通过 `GltfContainer` 组件需通过以下语句导入：

`import { GltfContainer } from "@dcl/sdk/ecs"`

有关如何轻松处理这些内容，请参阅 [导入](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/ru-men/coding-scenes.md#imports) 。
{% endhint %}

### 预加载 3D 模型

某些情况下，场景中会添加自定义 3D 模型，但不会立即使用。例如，自定义椅子模型可能只有在玩家与另一个物体互动时才会加载。在这种情况下，首次互动可能需要等待一段时间，直到模型下载并加载完成。

为避免这种情况，请使用 `AssetLoad.create` 方法，确保在需要资源之前将其下载。

```ts
import { AssetLoad } from "@dcl/sdk/ecs"

AssetLoad.create(engine.RootEntity, {
  assets: [
    "assets/scene/bundle1/explosion.glb",
  ],
})
```

如需了解更多信息，请参阅 [预加载资源](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/you-hua/pre-load-resources.md) 文档。

### 免费的 3D 模型库

除了自行制作 3D 模型，你也可以从多个免费或付费素材库下载模型。

以下列出了一些免费或价格相对低廉的素材库，供你入门参考：

* [IWB Catalog](https://dcl-iwb.co/)
* [Asset Ovi](https://assetovi.com/)
* [Builder 中的素材](https://github.com/decentraland/builder-assets/tree/master/assets)
* [SketchFab](https://sketchfab.com/)
* [Clara.io](https://clara.io/)
* [Archive3D](https://archive3d.net/)
* [SketchUp 3D Warehouse](https://3dwarehouse.sketchup.com/)
* [Thingiverse](https://www.thingiverse.com/) （主要为 3D 打印制作的 3D 模型，但可调整后用于虚拟世界）
* [ShareCG](https://www.sharecg.com/)
* [CGTrader](https://www.cgtrader.com/)

{% hint style="warning" %}
**📔 注意**：请留意下载内容的许可限制。
{% endhint %}

请注意，在其中一些网站上，你可以选择模型的下载格式。如有提供，请务必选择 *.glTF* 格式。如果没有该格式，则必须先将模型转换为 *glTF* 格式才能在场景中使用。为此，我们建议将模型导入 Blender，然后从中导出为 *.glTF* 格式。

### 优化 3D 模型

为确保场景中的 3D 模型加载更快且占用更少内存，请遵循以下最佳实践：

* 将模型保存为 *.glb* 格式，它是 *.gltf*.
* 如果有多个模型共用相同的纹理，请将模型导出为纹理单独存储的文件。这样，多个模型便可引用同一个纹理文件，而该文件只需加载一次。
* 如果场景中有时隐时现的实体，可以考虑将这些实体放入对象池，并将它们放在地下或将缩放比例设为 0。这样可以让它们更快显现；代价是它们在未使用时仍会占用内存。

## 拉伸形状

基本形状和 3D 模型都有默认尺寸，你可以通过更改实体的 `Transform` 组件中的缩放比例来调整这些尺寸。

```ts
const primitiveEntity = engine.addEntity()

MeshRenderer.setBox(primitiveEntity)

Transform.create(primitiveEntity, {
	position: { x: 8, y: 1, z: 8 },
	scale: { x: 4, y: 0.5, z: 4 },
})
```

## 设为不可见

为实体添加 `VisibilityComponent`，并将其 `visible` 属性设为 *false*.

```ts
const myEntity = engine.addEntity()
Transform.create(myEntity, {
	position: Vector3.create(4, 0, 4),
})
MeshRenderer.setBox(myEntity)

VisibilityComponent.create(myEntity, { visible: false })
```

对于带有基本形状或 `VisibilityComponent` 的实体，该组件的作用相同。 `GLTFContainer` 组件。

如果实体不可见，其碰撞体仍可能阻挡玩家的路径，和/或阻止玩家点击其后方的实体；具体取决于分配给碰撞体的碰撞层。

### 传播可见性

你可以使用 `propagateToChildren` VisibilityComponent `上的` 字段，将配置应用于实体子级树中的所有子级。如果 `propagateToChildren` propagateToChildren *true*，这些设置将向下应用于所有层级的所有子级。这样可以省去逐个将每个子实体标记为不可见或可见的繁琐操作。

```ts
// 父实体（显式设为不可见）
const parentEntity = engine.addEntity()
Transform.create(parentEntity, {
	position: Vector3.create(4, 0, 4),
})
MeshRenderer.setBox(parentEntity)
VisibilityComponent.create(parentEntity, { visible: false, propagateToChildren: true })

// 子实体（由于父实体而隐式不可见）
const child = engine.addEntity()
Transform.create(child, {
	position: Vector3.create(0, 1, 0),
	parent: parentEntity
})
MeshRenderer.setBox(child)
```

{% hint style="warning" %}
**📔 注意**：如果实体有自己的 `VisibilityComponent`，则其设置会覆盖父级的所有配置。

如果实体没有自己的 `VisibilityComponent`，其可见性由最近的、具有 `VisibilityComponent` 和 `propagateToChildren` 设为 *true*.
{% endhint %}

## 加载状态

如果 3D 模型相当大，渲染可能需要一些时间，具体耗时取决于玩家的硬件以及许多其他因素。有时，你需要确保模型加载完成后再执行其他操作。例如，如果你想将玩家传送到高空中的平台，就需要先确保平台已完全渲染，再将玩家移过去，否则玩家可能会直接穿过平台掉下去。

若要检查 3D 模型是否已完成渲染，请检查实体的 `GltfContainerLoadingState` 组件。此组件只读，存在于所有同时具有 `GltfContainer`组件的实体上。

此组件只有一个名为 `currentState`的属性，其值来自 `LoadingState` 枚举。

以下示例使用一个系统定期检查实体 3D 模型的加载状态。如果状态为 `LoadingState.FINISHED`，你可以在此处执行自定义逻辑，然后结束系统的执行。

```ts
export function main() {
	const meshEntity = engine.addEntity()
	GltfContainer.create(meshEntity, { src: 'models/Monster.glb' })
	engine.addSystem((deltaTime) => {
		const loadingState = GltfContainerLoadingState.getOrNull(meshEntity)
		if (!loadingState) return
		switch (loadingState.currentState) {
			case LoadingState.LOADING:
				console.log('mesh is LOADING')
				break
			case LoadingState.FINISHED:
				console.log('mesh is FINISHED')
				// Perform custom logic
				break
			case LoadingState.FINISHED_WITH_ERROR:
				console.log('mesh is FINISHED BUT MAY HAVE PROBLEMS')
				break
			case LoadingState.UNKNOWN:
				console.log('mesh is in an UNKNOWN STATE')
				break
		}
	})
}
```

## 高级语法

创建 `MeshRenderer` 组件的完整语法（不使用任何简化语法的辅助函数）如下所示：

```ts
MeshRenderer.create(myBox, {
	mesh: {
		$case: 'box',
		box: { uvs: [] },
	},
})

MeshRenderer.create(myPlane, {
	mesh: {
		$case: 'plane',
		plane: { uvs: [] },
	},
})

MeshRenderer.create(myShpere, {
	mesh: {
		$case: 'sphere',
		sphere: {},
	},
})

MeshRenderer.create(myCylinder, {
	mesh: {
		$case: 'cylinder',
		cylinder: {},
	},
})
```

基础协议就是这样解析 MeshRenderer 组件的。辅助函数封装了这些细节，并提供更易用的语法，但在底层，它们输出的仍是这种语法。

这个 `$case` 字段允许你指定一种受支持的类型。每种类型支持不同的一组参数。在上面的示例中， `box` 类型支持 `uvs` 字段。

$case `所支持的值如下：` 分别为：

* `box`
* `plane`
* `sphere`
* `cylinder`

根据 `$case`的值，可以为相应的形状定义对象，并传入任何相关属性。

要向一个可能已包含此组件实例的实体添加 `MeshRenderer` 组件，请使用 `MeshRenderer.createOrReplace()`。诸如 `MeshRenderer.setBox()` 这样的辅助函数会处理现有组件实例的覆盖；但如果对已包含此组件的实体调用 `MeshRenderer.create()` ，则会返回错误。


---

# 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/3d-nei-rong-ji-chu/shape-components.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.
