> 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/entity-positioning.md).

# 实体定位

如何设置场景中实体的位置、旋转和缩放

您可以设置 *位置*, *旋转* 和 *缩放* ，方法是使用 `Transform` 组件。它可以用于 3D 空间中的任何实体，并影响实体的渲染位置。适用对象包括基本形状（立方体、球体、平面等）、3D 文本形状、NFT 形状和 3D 模型（`GltfContainer`).

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

通过场景编辑器向场景添加项目时，该项目会自动包含一个 **Transform** 组件。您可以通过更改实体的位置、旋转或缩放值，间接修改其 Transform 组件中的值。您也可以在场景编辑器的 UI 中输入数值，以获得更高的精度。

## 代码要点

![](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)

```ts
// 创建一个新实体
const ball = engine.addEntity()

// 为实体添加形状，使其可见
MeshRenderer.setSphere(ball)

// 为实体添加 Transform 组件
Transform.create(ball, {
	position: Vector3.create(5, 1, 5),
	scale: Vector3.create(1, 1, 1),
	rotation: Quaternion.Identity(),
})
```

若要在一段时间内移动、旋转或调整场景中实体的大小，请逐帧递增地更改此组件中的值。详见 [移动实体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/move-entities.md) ，了解更多详情和最佳实践。

任何未指定的字段都会使用其默认值：position `0, 0, 0`、不旋转，缩放值为 `1, 1, 1`。请省略字段，而不要将其设为 `undefined`。显式设为 `undefined`的字段（例如，使用尚未赋值的变量）会覆盖默认值，随后场景会在下一次引擎更新时抛出错误，而不是在调用 `Transform.create()`.

```ts
// ❌ 如果 savedRotation 是 undefined，场景稍后会抛出错误
Transform.create(ball, { position: Vector3.create(5, 1, 5), rotation: savedRotation })

// ✅ 使用有效值作为回退值
Transform.create(ball, { position: Vector3.create(5, 1, 5), rotation: savedRotation ?? Quaternion.Identity() })
```

{% hint style="warning" %}
**📔 注意**: `Vector3` 和 `Quaternion` 必须通过以下语句导入：

> `import { Vector3, Quaternion } from "@dcl/sdk/math"`

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

## 位置

`position` 是一个 *三维向量*，用于设置实体中心在三个轴上的位置： *x*, *y*、以及 *z*。请参阅 [几何类型](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/special-types.md) 了解详情。

```ts
// 创建一个新实体
const ball = engine.addEntity()

// 使用预定义位置创建变换
Transform.create(ball, {
	  position: Vector3.create(5, 1, 5)
})

// 获取变换的可变版本
const mutableTransform = Transform.getMutable(ball)

// 使用对象设置位置
mutableTransform.position = { x: 5, y: 1, z: 5 }

// 使用对象设置位置（替代语法）
mutableTransform.position = Vector3.create(2, 1, 4)

// 分别设置各个轴
mutableTransform.position.x = 3
mutableTransform.position.y = 1
mutableTransform.position.z = 3
```

设置位置时，请注意以下事项：

* 位置向量中的数字表示 *米* （除非该实体是缩放实体的子级）。
* 由单个地块构成的场景尺寸为 16 米 x 16 米。场景中心（地面高度）位于 `x:8, y:0, z:8`。如果场景由多个地块构成，中心位置则取决于这些地块的排列方式。
* `x:0, y:0, z:0` 指的是场景基准地块在地面高度的 *西南* 角。

  > 提示：查看场景预览时，场景的 (0,0,0) 点会显示一个指南针，并标出各个轴以供参考。

  > 注意：你可以通过编辑 `base` 的属性来更改场景的基准地块，属性位于 *scene.json*.
* 为了更好地辨别方向，请使用你的 *左* 手：
  * 食指（向前指）代表 *z* 轴，
  * 中指（向侧面指）代表 *x* 轴，
  * 拇指（向上指）代表 *y* 轴。
* 如果某个实体是另一个实体的子级，那么 `x:0, y:0, z:0` 指的是其父实体的中心，无论父实体位于场景中的哪个位置。
* 场景中的每个实体都必须始终位于其所占地块的边界内。如果实体超出这些边界，就会引发错误。

  > 提示：在预览模式下查看场景时，超出边界的实体会以 *红色*.
* 场景的高度也有限制。无论场景占用多少块地块，每个场景的最大高度都是 330 米。放置在 200 米以上的实体可能会出现多人游戏同步问题。详情请参阅 [场景限制](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/you-hua/scene-limitations.md) 。

## 旋转

`rotation` 以 [*四元数*](https://en.wikipedia.org/wiki/Quaternion)的形式存储，它由四个数字组成： *x*, *y*, *z* 和 *w*。这些数字的取值范围均为 -1 到 1。详情请参阅 [几何体类型](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/special-types.md) 。

```ts
// 创建一个新实体
const cube = engine.addEntity()

// Create transform with a predefined rotation of 0
Transform.create(cube, {
	  rotation: Quaternion.Identity()
})

// 获取变换的可变版本
const mutableTransform = Transform.getMutable(cube)

// Set the rotation with an object, from euler angles
mutableTransform.rotation = Quaternion.fromEulerDegrees(0, 90, 0)

// Set the rotation with an object
mutableTransform.rotation = { x: 0.1, y: 0.5, z: 0.5, w: 0 }

// 分别设置各个轴
mutableTransform.rotation.x = 0
mutableTransform.rotation.y = 1
mutableTransform.rotation.z = 0.3
mutableTransform.rotation.w = 0
```

你也可以将旋转字段设置为 [*欧拉* 角](https://en.wikipedia.org/wiki/Euler_angles)，这是更常见的 *x*, *y* 和 *z* 表示法，使用的数字范围为 0 到 360，这是大多数人熟悉的表示法。使用欧拉角时，可以采用以下任一种表示法：

```ts
// Create transform with a predefined rotation in Euler angles
Transform.create(cube, {
	  rotation: Quaternion.fromEulerDegrees(0, 90, 0)
})

// 获取变换的可变版本
const mutableTransform = Transform.getMutable(cube)

// Set the rotation with an object, from euler angles
mutableTransform.rotation = Quaternion.fromEulerDegrees(0, 90, 0)
```

使用 *三维向量* 表示欧拉角时， *x*, *y* 和 *z* 分别表示绕对应轴旋转的角度，单位为度。旋转一整圈需要 360 度。

获取实体的旋转值时，默认返回的是四元数。若要以欧拉角表示旋转，请使用 `Quaternion.toEulerAngles()`:

```ts
// Fetch a read-only version of the transform
const transform = Transform.get(cube)

// 获取以欧拉角表示的旋转
const eulerAngle = Quaternion.toEulerAngles(transform.rotation)
```

## 获取实体的全局位置和旋转

这两个 `getWorldPosition` 和 `getWorldRotation` 函数会返回实体的全局位置和旋转。也就是说，它们会返回玩家看到该物体时感知到的位置或旋转，不考虑任何父级层级结构。

* `getWorldPosition(engine, entity: Entity): Vector3Type`：此函数返回实体的世界位置，并将其所有父实体的位置（如果有）考虑在内，返回 `{x: 0, y: 0, z: 0}` 如果实体没有 Transform。

```ts
const worldPos = getWorldPosition(engine, childEntity)
console.log(`World position: ${worldPos.x}, ${worldPos.y}, ${worldPos.z}`)
```

* `getWorldRotation(engine, entity: Entity): QuaternionType`：此函数返回实体的世界旋转，并考虑其所有父实体的旋转（如果该实体有父实体）。它返回一个 `Quaternion` 类型；如果实体没有 Transform，则返回单位四元数 `{x: 0, y: 0, z: 0, w: 1}` 。

```ts
const worldRot = getWorldRotation(engine, childEntity)
console.log(`World rotation: ${worldRot.x}, ${worldRot.y}, ${worldRot.z}, ${worldRot.w}`)
```

{% hint style="info" %}
**注意：** 全局位置和全局旋转是相对于场景内部的坐标，而不是 Genesis City。
{% endhint %}

## 面向玩家

为实体添加 *Billboard* 组件，使其始终旋转并面向玩家的摄像机。

Billboard 是 90 年代 3D 游戏中常见的一种技术，当时大多数实体都是始终面向玩家的 2D 平面。同样的思路也可用于旋转 3D 模型。

{% hint style="warning" %}
**📔 注意**：广告牌朝向 **摄像机**，而不是头像。在第三人称视角中，摄像机位于头像后上方，因此两者的位置不同，朝向摄像机的广告牌看起来会明显偏离头像。若要让广告牌朝向头像，请将 `targetEntity` 设为 `engine.PlayerEntity`.
{% endhint %}

```ts
// 创建一个新实体
const cube = engine.addEntity()

// 为实体设置可见形状
MeshRenderer.setBox(cube)

// 使用预定义位置创建变换
Transform.create(cube, {
	  position: Vector3.create(5, 1, 5)
})

// 为实体添加 Billboard 组件
Billboard.create(cube, {})
```

你可以通过以下参数配置广告牌的行为：

* `billboardMode`：使用 `BillboardMode` 中的值，设置自动旋转以面向玩家的旋转轴：
  * `BillboardMode.BM_ALL`：实体会绕所有旋转轴旋转以面向玩家。如果玩家位于实体上方较高处，实体会朝上。
  * `BillboardMode.BM_NONE`：实体不会旋转。
  * `BillboardMode.BM_X`：实体仅绕其 *x* 旋转轴。
  * `BillboardMode.BM_Y`：实体只绕其 *y* 旋转轴旋转。它只会左右转动，不会上下转动。即使玩家位于实体的上方或下方，它也会保持与地面垂直。
  * `BillboardMode.BM_Z`：实体只绕其 *z* 旋转轴旋转。
* `targetEntity`：（可选）公告板要朝向的实体，而非玩家的摄像机。如果所引用的实体不存在（例如，尚未创建或已被移除），公告板会停止旋转，并保持最后的朝向，直到该实体重新存在。将此项设为 `engine.CameraEntity` 等同于不设置此项。

```ts
// 平面公告板
const perpendicularPlane = engine.addEntity()

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

MeshRenderer.setPlane(perpendicularPlane)

Billboard.create(perpendicularPlane, {
	billboardMode: BillboardMode.BM_Y,
})

// 文本标签
const textLabel = engine.addEntity()

Transform.create(textLabel, {
	position: Vector3.create(6, 1, 6),
})

TextShape.create(textLabel, {
	text: 'This text is always readable',
})

Billboard.create(textLabel)

// 朝向另一个实体而非玩家的标牌
const sphere = engine.addEntity()

Transform.create(sphere, {
	position: Vector3.create(4, 2, 4),
})

MeshRenderer.setSphere(sphere)

const sign = engine.addEntity()

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

TextShape.create(sign, {
	text: 'Watching the sphere',
})

Billboard.create(sign, {
	targetEntity: sphere,
})
```

{% hint style="info" %}
**💡 提示**：公告板非常适合添加到 *文本* 实体上，因为这样可以让它们始终清晰易读。
{% endhint %}

将 `targetEntity` 设为 `engine.PlayerEntity` ，即可让公告板跟随化身，而非摄像机。对于名牌、对话气泡，或其他应跟随化身而非玩家视角的内容，这正是你需要的设置：

```ts
// 朝向化身而非摄像机的标签
Billboard.create(label, {
	targetEntity: engine.PlayerEntity,
	billboardMode: BillboardMode.BM_Y,
})
```

化身的位置在脚部，因此放在头顶上方的标签会向下倾斜，朝向化身。 `BM_Y` 会让标签保持直立，并且只左右转动。

### 公告板的朝向

广告牌会将其局部 **-Z** 轴指向它所朝向的方向。当你将其他实体设为广告牌的子级时，这一点很重要：

* 局部位置为 **+Z** 的子级会位于广告牌 **后方** ，被广告牌遮挡。
* 局部位置为 **-Z** 的子级会位于广告牌 **前方**，离观察者更近。

因此，若要将边框或背景放在广告牌标签后方，请沿 **+Z**方向偏移。若要在它前方添加高亮效果，请沿 **-Z**.

当广告牌跟随玩家移动时，实体的 `rotation` 值不会改变， `Transform` 组件也是如此。

如果实体同时具有 `Billboard` 组件和带有 `Transform` 组件，且其中包含 `rotation` 值，那么玩家会看到实体作为广告牌旋转。如果广告牌未影响所有坐标轴，剩余坐标轴将根据 `Transform` 组件旋转。

{% hint style="warning" %}
**📔 注意**：如果同一时间有多个玩家，每位玩家都会看到广告牌模式的实体朝向自己。广告牌的旋转会针对每位玩家在本地单独计算，不会影响其他玩家看到的效果。此规则不适用于带有 `targetEntity`的广告牌：由于目标的位置属于场景的一部分，所有玩家看到的这些广告牌朝向都相同。
{% endhint %}

## 朝向一组坐标

要让实体 A 朝向实体 B：

```
1) 用实体 B 的位置减去实体 A 的位置，得到一个表示两者间距离的向量。
2) 将该向量归一化，使其长度为 1，同时保持方向不变。
3) 使用 `Quaternion.lookRotation` 获取一个描述朝向该方向的旋转四元数。
4) 将该四元数设为实体 A 的旋转
```

```ts
export function turn(entity: Entity, target: Vector3.ReadonlyVector3) {
	const transform = Transform.getMutable(entity)
	const difference = Vector3.subtract(target, transform.position)
	const normalizedDifference = Vector3.normalize(difference)
	transform.rotation = Quaternion.lookRotation(normalizedDifference)
}
```

## 缩放

`scale` 也是一个 *三维向量*，以 `Vector3` 对象，包括 *x*, *y* 和 *z* 轴上的缩放系数。实体的形状会相应缩放，无论它是基本图形还是 3D 模型。

默认缩放值为 1，因此，赋予实体大于 1 的值可以拉伸实体，小于 1 的值则可以缩小实体。

```ts
// 创建一个新实体
const ball = engine.addEntity()

// 使用预定义位置创建变换
Transform.create(ball, {
	  scale: Vector3.create(5, 5, 5)
})

// 获取变换的可变版本
const mutableTransform = Transform.getMutable(ball)

// Set the scale with a Vector3

mutableTransform.scale = Vector3.create(2, 2, 2)

// 使用对象设置位置
mutableTransform.scale = { x: 5, y: 1, z: 5 }

// 分别设置各个轴
mutableTransform.scale.x = 3
mutableTransform.scale.y = 3
mutableTransform.scale.z = 2
```

## 继承父级变换

当一个实体嵌套在另一个实体中时，子实体会继承父实体的组件。这意味着，如果父实体被定位、缩放或旋转，其子实体也会受到影响。子实体的位置、旋转和缩放值不会覆盖父实体的值，而是与其叠加。

通过设置子实体上的 `parent` 字段，可以将一个实体指定为另一个实体的父实体。该字段位于子实体的 `Transform` 组件上。

如果父实体经过缩放，其所有子实体的位置值也会随之缩放。

```ts
// Create entities
const parentEntity = engine.addEntity()
const childEntity = engine.addEntity()

// Create a transform for the parent
Transform.create(parentEntity, {
	position: Vector3.create(3, 1, 1),
	scale: Vector3.create(0.5, 0.5, 0.5),
})

// Create a transform for the child, and assign it as a child
Transform.create(childEntity, {
	position: Vector3.create(0, 1, 0),
	parent: parentEntity,
})
```

在此示例中，子实体会缩小到 0.5 倍，因为其父实体的缩放值为 0.5。子实体的位置也会相对于父实体计算。我们需要将父实体的位置与子实体的位置相加。在本例中，由于父实体缩小到原来的一半，子实体的变换也会按比例缩小。以绝对坐标表示，子实体的位置为 `{ x: 3, y: 1.5, z: 1 }`。如果父实体设置了 `rotation`，也会影响子实体的最终位置，因为旋转会改变子实体偏移所沿的轴。

如果子实体的 Transform 上没有 `position` ，则其默认值为 `0,0,0`，这会使子实体与父实体位于同一位置。

你可以使用一个不带形状组件的不可见实体作为父实体，将一组其他实体组合起来。该实体不会显示在渲染场景中，但可以用来将其子实体分组，并为它们统一应用变换。

{% hint style="warning" %}
**📔 注意**：避免在层级结构中创建循环，即某个实体最终成为自己的祖先。SDK 会检测此类循环，并记录警告，指出涉及的实体。在修正父子关系之前，受影响的实体将无法正确定位。
{% endhint %}

## 将实体附加到化身

将实体附加到玩家有三种方法：

* 将其设为以下对象的子实体： **Avatar Entity**
* 将其设为以下对象的子实体： **Camera Entity**
* 使用 **AvatarAttach 组件**

将实体附加到化身的最简单方法是将父实体设置为 [保留实体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/entities-components.md#reserved-entities) `engine.PlayerEntity`。此后，该实体将随玩家的位置一起移动。

```ts
let childEntity = engine.addEntity()

MeshRenderer.setCylinder(childEntity)

Transform.create(childEntity, {
	scale: Vector3.create(0.2, 0.2, 0.2),
	position: Vector3.create(0, 0.4, 0),
	parent: engine.PlayerEntity,
})
```

你还可以将实体设置为 [保留实体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/entities-components.md#reserved-entities) `engine.CameraEntity`。在第一人称视角中使用相机实体时，附加的实体会跟随相机移动。这非常适合让某个物体始终保持在视野中，例如让枪械的 3D 模型始终可见，即使相机朝上看时也是如此。

```ts
let childEntity = engine.addEntity()

MeshRenderer.setCylinder(childEntity)

Transform.create(childEntity, {
	scale: Vector3.create(0.2, 0.2, 0.2),
	position: Vector3.create(0, 0.4, 0),
	parent: engine.CameraEntity,
})
```

若要将对象附加到化身的某根骨骼上，并使其随化身的动画一起移动，请向该实体添加 `AvatarAttach` 组件。

你可以选择化身上的不同锚点，其中大多数锚点都关联到玩家的骨架，并会跟随玩家的动画。例如，使用右手锚点时，附加的实体会在化身挥手或跑步时摆动手臂的过程中随之移动，就像玩家手持该实体一样。

```ts
// 附加到主玩家；如果未设置 avatarId，则默认使用 engine.PlayerEntity
AvatarAttach.create(myEntity, {
	anchorPointId: AvatarAnchorPointType.AAPT_NAME_TAG,
})

// 按 ID 附加到玩家
AvatarAttach.create(myEntity, {
	avatarId: '0xAAAAAAAAAAAAAAAAA',
	anchorPointId: AvatarAnchorPointType.AAPT_NAME_TAG,
})
```

创建 `AvatarAttach` 组件时，请传入一个包含以下数据的对象：

* `avatarId`: *可选* 要附加到的玩家 ID。对于使用以太坊钱包连接的玩家，此 ID 与玩家的以太坊地址相同。如果未指定，则会将实体附加到本地玩家的化身上。
* `anchorPointId`：实体在化身骨架上的附加锚点，使用枚举 `AvatarAnchorPointType`.

{% hint style="warning" %}
**📔 注意**：如果你希望场景中的所有玩家都能看到附加到同一玩家身上的对象，例如让所有人都看到玩家 A 拾起一个物体并将其拿在左手中，那么必须为 `avatarId`提供一个值。如果未指定，所有玩家都会看到该对象附加在自己的化身上。
{% endhint %}

以下示例将一个实体附加到特定化身上，以便其他所有玩家都能看到它附加在同一个化身上。

```ts
import { getPlayer } from '@dcl/sdk/src/players'
import { AvatarAnchorPointType, AvatarAttach, engine, Entity } from '@dcl/sdk/ecs'
import { syncEntity } from '@dcl/sdk/network'

async function attachToPlayer(){

 let userData = await getPlayer()
 console.log(userData)

 if (!userData || !userData.wearables) return

  let entity = engine.addEntity()

  AvatarAttach.create(entity, {
    avatarId: userData.userId,
    anchorPointId: AvatarAnchorPointType.AAPT_RIGHT_HAND,
  })

  // 其他组件

  syncEntity(entity, [AvatarAttach.componentId])

}
```

以下锚点可用于 `AvatarAnchorPointType` 枚举：

* `AAPT_RIGHT_HAND`：固定在玩家的右手上
* `AAPT_LEFT_HAND`：固定在玩家的左手上
* `AAPT_HEAD`：固定在玩家头部中央。
* `AAPT_NECK`：固定在玩家颈根处。
* `AAPT_SPINE`：固定在脊柱上段。
* `AAPT_SPINE1`：固定在脊柱中段。
* `AAPT_SPINE2`：固定在脊柱下段。
* `AAPT_HIP`：固定在髋骨上。
* `AAPT_LEFT_SHOULDER`：固定在左肩上。
* `AAPT_LEFT_ARM`：固定在左侧第一根手臂骨骼上，位于肩部高度。
* `AAPT_LEFT_FOREARM`：固定在左前臂骨骼上。
* `AAPT_LEFT_HAND_INDEX`：固定在左手食指指尖。
* `AAPT_RIGHT_SHOULDER`：固定在右肩上。
* `AAPT_RIGHT_ARM`：固定在右侧第一根手臂骨骼上，位于肩部高度。
* `AAPT_RIGHT_FOREARM`：固定在右前臂骨骼上。
* `AAPT_RIGHT_HAND_INDEX`：固定在右手食指指尖。
* `AAPT_LEFT_UP_LEG`：固定在左腿上部的腿骨上。
* `AAPT_LEFT_LEG`：固定在左腿下部的腿骨上。
* `AAPT_LEFT_FOOT`：固定在左脚踝处。
* `AAPT_LEFT_TOE_BASE`：固定在左脚脚趾尖端。
* `AAPT_RIGHT_UP_LEG`：固定在右腿上部的腿骨上。
* `AAPT_RIGHT_LEG`：固定在右腿下部的腿骨上。
* `AAPT_RIGHT_FOOT`：固定在右脚踝处。
* `AAPT_RIGHT_TOE_BASE`：固定在右脚脚趾尖端。
* `.AAPT_NAME_TAG`：悬浮在玩家名牌正上方，不受玩家动画影响。

  > 注意：名牌的高度会根据玩家穿戴物品的高度动态调整。因此，戴高帽子的玩家，其名牌会比其他玩家稍高一些。
* `AAPT_POSITION` *已弃用*：玩家的整体位置。该位置位于玩家脚部上方 0.8 个单位处。

  >

{% hint style="warning" %}
\> \*\*📔 注意\*\*：\`AAPT\_POSITION\` 已弃用。若要跟随玩家的整体位置，最好将实体设为 Avatar Entity 的子级。示例请参阅本节开头。>
{% endhint %}

{% hint style="info" %}
**💡 提示**：若要使用这些值，请输入 `AvatarAnchorPointType.` VS Code 会在下拉列表中显示完整的选项列表。
{% endhint %}

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

实体渲染由场景的每个实例在本地独立决定。将实体附加到一名玩家身上，不会让正在观看该玩家的其他玩家也看到该实体。如果实体附加到默认本地玩家，每名玩家都会看到该实体附加在自己的化身上。

{% hint style="warning" %}
**📔 注意**：附加到化身的实体必须保持在场景范围内才能渲染。如果玩家走出场景，所有附加实体都会停止渲染，直到玩家走回场景。智能可穿戴设备不受此限制。
{% endhint %}

AvatarAttach `AvatarAttach` 组件会覆盖 `Transform` 组件中的值。你在 `Transform` 组件中设置的任何值，都会被实体相对于玩家 Transform 的位置取代；玩家移动和播放动画时，这些值会逐帧更新。

如果需要让实体相对于化身上的锚点偏移，或设置不同的旋转或缩放，请通过父实体来实现。

1. 创建一个仅包含 `Transform` 和 `AvatarAttach` 组件的不可见实体。玩家移动时，它的 `Transform` 值会被覆盖
2. 将要附加的实体设为此父实体的子级。其 `Transform` 值可用于描述相对于锚点的偏移。

```ts
// 创建父实体
const parentEntity = engine.addEntity()

// 将父实体附加到玩家
AvatarAttach.create(parentEntity, {
	anchorPointId: AvatarAnchorPointType.AAPT_NAME_TAG,
})

// 创建子实体
let childEntity = engine.addEntity()

MeshRenderer.setCylinder(childEntity)

Transform.create(childEntity, {
	scale: Vector3.create(0.2, 0.2, 0.2),
	position: Vector3.create(0, 0.4, 0),
	parent: parentEntity,
})
```

{% hint style="warning" %}
**📔 注意**：如果附加的实体带有碰撞体，这些碰撞体可能会阻挡玩家移动或导致抖动。你可以考虑禁用附加实体碰撞体的物理层。请参阅 [碰撞层](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md#collision-layers)
{% endhint %}

{% hint style="warning" %}
**📔 注意**：如果你有一个子实体，并且想要获取它的全局位置和/或旋转，可以使用 `getWorldPosition` 和 `getWorldRotation` 函数。请参阅 [获取全局位置和旋转](#getting-global-position-and-rotation-of-an-entity) 一节。
{% endhint %}

### 附加到其他玩家

你可以使用 `AvatarAttach` 组件将实体附加到另一名玩家身上。为此，你必须知道该玩家的 ID。

若要将实体附加到另一名玩家的化身，必须在 `avatarId`字段中提供用户 ID。获取此数据有 [多种方法](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/user-data.md#get-player-data) 。

{% hint style="warning" %}
**📔 注意**：对于使用以太坊钱包连接的玩家，其 `userId` 与其以太坊地址相同。
{% endhint %}

对于其他附近的玩家，可通过 `userId` 调用 `getPlayer()`

```ts
executeTask(async () => {
	for (const [entity, data] of engine.getEntitiesWith(PlayerIdentityData)) {
		console.log('Player id: ', data.address)
	}
})
```

结合使用 `AvatarAttach`，可以使用以下代码在场景中每位其他玩家的头顶添加一个悬浮的立方体：

```ts
executeTask(async () => {
        for (const [entity, data] of engine.getEntitiesWith(PlayerIdentityData)) {
            const myEntity = engine.addEntity()
            MeshRenderer.setBox(myEntity)
            AvatarAttach.create(myEntity, {
                anchorPointId: AvatarAnchorPointType.AAPT_LEFT_HAND,
                avatarId: data.address,
            })
        }
    })
```

如需了解获取其他用户 ID 的其他方式，请参阅 [获取玩家数据](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/user-data.md#get-player-data).

{% hint style="warning" %}
**📔 注意**：不要将其他玩家的实体设为你自己的实体的 `parent` 。引擎会写入该实体的 `Transform` 供场景读取，但它并不是可供你的实体挂接的父实体，因此子实体会回退到场景根节点，并停留在场景原点。请改用 `AvatarAttach` 并传入玩家地址，如上所示。
{% endhint %}

随着玩家加入和离开，玩家实体 ID 会被重复使用，因此同一个实体之后可能会属于不同的人。如果你为每位玩家保留一个标记，请存储创建该标记时使用的地址，并在每一帧进行比对。如果实体上的地址发生变化，请删除旧标记并创建一个新的：

```ts
import { AvatarAttach, AvatarAnchorPointType, engine, Entity, PlayerIdentityData } from '@dcl/sdk/ecs'

// 标记创建时对应的地址，以便识别被重复使用的实体 ID
const markers = new Map<Entity, { address: string; marker: Entity }>()

function markerSystem() {
	// 移除玩家已离开，或其实体 ID 现在属于其他玩家的标记
	for (const [player, entry] of markers) {
		if (PlayerIdentityData.getOrNull(player)?.address === entry.address) continue
		engine.removeEntity(entry.marker)
		markers.delete(player)
	}

	for (const [player, data] of engine.getEntitiesWith(PlayerIdentityData)) {
		if (markers.has(player)) continue
		const marker = engine.addEntity()
		AvatarAttach.create(marker, {
			avatarId: data.address,
			anchorPointId: AvatarAnchorPointType.AAPT_NAME_TAG,
		})
		markers.set(player, { address: data.address, marker })
	}
}

engine.addSystem(markerSystem)
```

## 场景边界

场景中的所有实体都必须位于场景边界内，因为边界之外是属于其他玩家的土地地块。

如果预览时模型的任何部分超出这些边界，超出的部分将被裁切且不会渲染；无论是在预览中还是在已发布的场景中都是如此。

实体移动时，系统会持续检查其在场景中的位置。如果实体离开场景后又返回，它会先被移除，然后再正常渲染。

场景地面上的网格显示了场景的边界。默认情况下，边界在 *x* 和 *z* 轴上从 0 延伸到 16，在 *y* 轴。你可以自由地将实体放置在地下，也就是 0 以下的 *y* 轴。

{% hint style="info" %}
**💡 提示**：如果场景需要更多地块，可以在项目的 `scene.json` 文件中添加。请参阅 [场景元数据](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/xiang-mu-lei-xing/scene-metadata.md) 了解具体操作。添加后，你应该会看到网格扩展，以覆盖新增的地块。
{% endhint %}


---

# 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/entity-positioning.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.
