> 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/jiao-hu-xing/raycasting.md).

# 射线投射

使用射线投射在空间中追踪一条线，并查询与场景中实体的碰撞。

射线检测是游戏开发中的基础工具。使用射线检测，你可以在空间中追踪一条虚拟直线，并查询是否有实体与这条直线相交。这对于计算视线、子弹轨迹、寻路算法以及许多其他应用都很有用。

当玩家按下指针按钮（主按钮或次按钮）时，系统会从玩家的位置沿其视线方向发射一条射线。有关详情，请参阅 [按钮事件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/click-events.md) 。本文档介绍如何从任意位置和方向发射不可见射线，不受玩家操作影响；你可以将其用于许多其他场景。

请注意，射线检测只能命中带有碰撞体的对象。因此，如果你要检测射线是否命中 3D 模型，可以采用以下任一方式：

* 模型必须包含 [碰撞网格](https://docs.decentraland.org/creator/content-creator-zh/3d-jian-mo-yu-dong-hua/colliders.md).
* 将 `GLTFContainer` 配置为使用 [带有碰撞掩码的可见几何体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md#colliders-on-3d-models).
* 添加 [MeshCollider 组件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md).

此外，最好为 3D 模型指定自定义 [碰撞层](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md#collision-layers) 这样射线只需检测相关实体的碰撞，而不必检测所有带有碰撞体的对象。

## 创建射线

每条射线都有一个起点和一个方向。起点基于实体的位置，取自实体的 Transform 组件中的值。射线方向可以通过以下 4 种方式定义：

* **局部方向**：相对于实体的朝前方向，并且也受任何父实体变换的影响。这适用于检测车辆前方的障碍物，同时遵循车辆的朝向。
* **全局方向**：忽略实体的旋转，方向如同实体的旋转为 0 时一样。例如，这适用于始终朝下的情况。
* **全局目标**：在实体的位置与场景中的全局目标位置之间追踪一条直线。忽略实体的旋转。例如，这适用于创建塔防游戏：每座塔的炮塔都可以指向空间中的一个精确坐标。
* **目标实体**：在实体的位置与另一个目标实体的位置之间追踪一条直线。忽略这两个实体的旋转。

以下代码使用局部方向创建射线检测：

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

raycastSystem.registerLocalDirectionRaycast(
  {
    entity: myEntity,
    opts: { direction: Vector3.Forward() },
  },
  function (raycastResult) {
    // 回调函数
  }
)
```

使用以下函数，通过不同方式指定方向来创建射线检测：

* `raycastSystem.registerLocalDirectionRaycast()`：创建具有 **局部** 方向的射线检测。 `direction` 字段需要一个 `Vector3` ，用于描述相对于实体及其旋转的向量（例如， `Vector3.Forward()` 最终会使用实体变换的前向向量）
* `raycastSystem.registerGlobalDirectionRaycast()`：创建具有 **全局** 方向的射线检测。 `direction` 字段应为 `Vector3` ，用于描述全局方向。
* `raycastSystem.registerGlobalTargetRaycast()`：创建射线，其方向由 **全局目标** 位置定义。 `target` 字段应为 `Vector3` ，用于描述场景中的全局位置。
* `raycastSystem.registerTargetEntityRaycast()`：创建射线，其方向指向 **目标实体** 的位置。 `targetEntity` 字段应为对实体的引用，该实体的位置将用作射线的目标。

使用上述任一方法创建射线时，还可设置以下可选字段：

* `maxDistance`: *数字* ，用于设置射线的追踪长度。若未设置，默认值为 16 米。
* `queryType`: *RaycastQueryType* 枚举值，用于指定射线返回所有命中的实体，还是仅返回第一个命中的实体。可选项如下：
  * `RaycastQueryType.RQT_HIT_FIRST`: *（默认）* 仅返回从起点开始遇到的第一个命中实体。
  * `RaycastQueryType.RQT_QUERY_ALL`：返回所有命中的实体，范围从起点直到射线的最大距离。
* `originOffset`：不从实体的原点位置开始射线检测，而是添加偏移量，从相对位置开始查询。例如，可以使用较小的偏移量，避免射线与实体自身的碰撞体发生碰撞。若未设置，默认值为 `Vector3.Zero()`.
* `collisionMask`：仅检测特定碰撞层上的碰撞。可将其与自定义碰撞层搭配使用，也可用来仅检测物理层或指针事件层。请参阅 [碰撞层](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md#collision-layers)。若未设置，默认使用的层为 `ColliderLayer.CL_PHYSICS`.
* `continuous`：若为 true，则每帧都会持续执行射线查询。若为 false，则射线仅在当前帧使用。若未设置，默认值为 false。
* 使用局部方向或全局方向设置方向时， `direction` 字段的默认值为 `Vector3.Forward()`.
* 使用全局目标设置方向时， `target` 字段的默认值为 `Vector3.Zero()`.
* 使用实体目标设置方向时， `targetEntity` 字段的默认值为场景根实体，该实体位于 `Vector3.Zero()`.

{% hint style="warning" %}
**📔 注意**： `continuous` 属性应谨慎使用，因为每帧都运行一次射线检测查询会严重影响性能。尽可能使用一个系统（或 Utils 库中的 `interval` 函数）以更稀疏的固定间隔运行射线检测查询，参见 [重复射线检测](#recurrent-raycasting).
{% endhint %}

以下示例展示了使用四种方法确定射线方向的方式：

```ts
// 局部方向射线检测
raycastSystem.registerLocalDirectionRaycast(
  {
    entity: myEntity,
    opts: {
      queryType: RaycastQueryType.RQT_QUERY_ALL,
      direction: Vector3.Forward(),
      maxDistance: 30,
    },
  },
  function (raycastResult) {
    console.log(raycastResult.hits)
  }
)
// 全局方向射线检测
raycastSystem.registerGlobalDirectionRaycast(
  {
    entity: myEntity,
    opts: {
      queryType: RaycastQueryType.RQT_QUERY_ALL,
      direction: Vector3.Forward(),
      maxDistance: 30,
    },
  },
  function (raycastResult) {
    console.log(raycastResult.hits)
  }
)
// 全局目标位置射线检测
raycastSystem.registerGlobalTargetRaycast(
  {
    entity: myEntity,
    opts: {
      queryType: RaycastQueryType.RQT_QUERY_ALL,
      target: Vector3.Zero(),
    },
  },
  (raycastResult) => {
    console.log(raycastResult.hits)
  }
)
// 目标实体射线检测
const targetEntity = engine.addEntity()
Transform.create(targetEntity, { position: Vector3.create(8, 1, 10) })

raycastSystem.registerTargetEntityRaycast(
  {
    entity: myEntity,
    opts: {
      queryType: RaycastQueryType.RQT_QUERY_ALL,
      targetEntity: targetEntity,
    },
  },
  (raycastResult) => {
    console.log(raycastResult.hits)
  }
)
```

{% hint style="warning" %}
**📔 注意**: `raycastSystem`, `RaycastQueryType` 和 `ColliderLayer` 必须通过

> `import { raycastSystem, RaycastQueryType, ColliderLayer } from "@dcl/sdk/ecs"`

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

## 射线检测结果

处理射线检测的回调函数会接收一个对象，其中包含射线本身的数据，以及被射线命中的所有实体。

* `globalOrigin`：射线的起始位置，以场景为参照。
* `direction`：射线所指向的全局方向，表示为一个 `Vector3`.
* `hits`：包含一个数组，每个被命中的实体对应一个对象。如果没有命中任何实体，此数组为空。如果射线检测使用了 `RaycastQueryType.RQT_HIT_FIRST`，此数组将只包含一个对象。

hits `hits` 数组中的每个对象都包含：

* `entityId`：被射线命中的实体的 ID 编号。
* `meshName`: *字符串* 其中包含 3D 模型中被命中的特定网格的内部名称。这在 3D 模型由多个网格组成时很有用。
* `position`: *Vector3* 表示射线与被命中实体相交的位置（相对于场景）
* `length`：射线从起点到与实体发生碰撞位置的长度。
* `normalHit`: *Vector3* 表示命中表面在世界坐标系中的法线。
* `globalOrigin`: *Vector3* 表示射线的起点位置（相对于场景）
* `direction`：射线所指向的全局方向，表示为一个 `Vector3`.

以下示例会遍历所有被命中的实体：

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

raycastSystem.registerLocalDirectionRaycast(
  {
    entity: myEntity,
    opts: {
      queryType: RaycastQueryType.RQT_QUERY_ALL,
      direction: Vector3.Forward(),
      maxDistance: 30,
    },
  },
  function (raycastResult) {
    if (raycastResult.hits.length > 0) {
      for (const hit of raycastResult.hits) {
        if (hit.entityId) {
          console.log('hit entity ', hit.entityId)
        }
      }
    } else {
      console.log('no entities hit')
    }
  }
)
```

{% hint style="warning" %}
**📔 注意**：射线投射结果也可能命中其他场景中的实体。
{% endhint %}

## 处理被命中的实体

当射线投射结果命中了实体时，可以使用 `entityId` 与该实体及其组件交互。实体 [不过是一个数字](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/entities-components.md#overview)，因此 `entityId` 该值本身可以解释为 `Entity` 类型。

```ts
const hitEntity = hit.entityId as Entity
const transform = Transform.get(hitEntity)
console.log(transform.position)
```

## 碰撞层

为了提升场景性能，最好只检查与当前相关实体之间的碰撞。 `collisionMask` 字段允许你仅指定特定的碰撞层：物理层（场景墙壁和地板）、指针层（指针事件）、玩家层（化身），或 8 个可自由分配的自定义层。请参阅 [碰撞层](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md#collision-layers).

默认情况下， `collisionMask` 字段设置为 `ColliderLayer.CL_PHYSICS`。你可以更改此值以指定其他层，也可以使用 `|` 分隔符组合多个层。

```ts
raycastSystem.registerLocalDirectionRaycast(
  {
    entity: myEntity,
    opts: {
      queryType: RaycastQueryType.RQT_QUERY_ALL,
      direction: Vector3.Forward(),
      maxDistance: 30,
      collisionMask:
        ColliderLayer.CL_CUSTOM1 |
        ColliderLayer.CL_CUSTOM3 |
        ColliderLayer.CL_POINTER,
    },
  },
  (raycastResult) => {
    log(raycastResult.hits)
  }
)
```

## 持续射线投射

使用 `raycastSystem`的函数时，默认行为是创建一条射线并仅查询一次碰撞。或者，你可以设置 `continuous` 字段设为 *true* ，即可在游戏循环的每个时钟周期运行查询和回调函数。

以下示例会从此时起持续运行射线投射查询

```ts
raycastSystem.registerLocalDirectionRaycast(
  {
    entity: myEntity,
    opts: {
      queryType: RaycastQueryType.RQT_QUERY_ALL,
      direction: Vector3.Forward(),
      maxDistance: 30,
      continuous: true,
    },
  },
  function (raycastResult) {
    log(raycastResult.hits)
  }
)
```

{% hint style="warning" %}
**📔 注意**： `continuous` 属性应谨慎使用，因为每帧都运行射线投射查询会对性能造成很大开销。
{% endhint %}

不再需要时，请移除所有重复执行的射线投射。为此，必须使用 `raycastSystem.removeRaycasterEntity`.

```ts
raycastSystem.removeRaycasterEntity(myEntity)
```

如果条件允许，请使用系统（或 Utils 库中的 `interval` 函数），以较稀疏且固定的间隔运行射线投射查询，例如每秒一次或每 0.2 秒一次。

```typescript
// 自定义组件
const CubeOscilator = engine.defineComponent('CubeOscilator', {
  t: Schemas.Float,
})

const TimerComponent = engine.defineComponent('TimerComponent', {
  t: Schemas.Float,
})

const RAY_INTERVAL = 0.1

// 检查射线
engine.addSystem((dt) => {
  for (const [entity] of engine.getEntitiesWith(TimerComponent)) {
    const timer = TimerComponent.getMutable(entity)
    timer.t += dt

    if (timer.t > RAY_INTERVAL) {
      timer.t = 0
      raycastSystem.registerGlobalDirectionRaycast(
        {
          entity: myEntity,
          opts: {
            queryType: RaycastQueryType.RQT_HIT_FIRST,
            direction: Vector3.Forward(),
            maxDistance: 16,
          },
        },
        function (raycastResult) {
          log(raycastResult.hits)
        }
      )
    }
  }
})

TimerComponent.create(engine.addEntity())

// 振荡立方体系统
engine.addSystem((dt) => {
  for (const [entity, cube] of engine.getEntitiesWith(
    CubeOscilator,
    Transform
  )) {
    CubeOscilator.getMutable(entity).t += dt
    Transform.getMutable(entity).position.y = 2 + Math.cos(cube.t)
  }
})

// 创建立方体
const cubeEntity = engine.addEntity()
Transform.create(cubeEntity, { position: { x: 8, y: 1, z: 8 } })
CubeOscilator.create(cubeEntity)
MeshRenderer.setBox(cubeEntity)
MeshCollider.setBox(cubeEntity)
```

上面的示例每 0.1 秒执行一次重复的射线投射。它使用计时器组件和系统的 `dt` 属性来确保这些操作按固定间隔进行。示例还包含一个由另一个系统控制、上下振荡的立方体，使其移入和移出射线路径。

{% hint style="info" %}
**💡 提示**：使用 `interval` 函数（位于 [SDK Utils 库](https://github.com/decentraland/sdk7-utils) 以更简单的方式按固定间隔运行函数。
{% endhint %}

## 通过系统执行射线检测

执行重复射线检测的另一种方式，是在系统的重复函数中执行检测。这样，你可以更灵活地控制检测的时机和方式。你无需注册回调函数，而是可以使用 `raycastSystem.registerRaycast` 执行射线检测查询，然后在系统函数中检查该操作返回的数据。

请注意，由于射线检测是在系统中执行的，结果要到下一个 tick 才会可用，因此系统需要运行两次：第一次为下一帧注册射线检测，下一帧则处理其结果。

```ts
engine.addSystem((deltaTime) => {
		const result = raycastSystem.registerRaycast(
			myEntity,
			raycastSystem.localDirectionOptions({
				collisionMask: ColliderLayer.CL_CUSTOM1 | ColliderLayer.CL_CUSTOM3 | ColliderLayer.CL_POINTER,
				originOffset: Vector3.create(0, 0.4, 0),
				maxDistance: 16,
				queryType: RaycastQueryType.RQT_HIT_FIRST,
				direction: Vector3.Forward(),
				continuous: true // don't overuse the 'continuous' property as raycasting is expensive on performance
			})
		)
		if (result) {
			// do something
		}
	})
```

## 与玩家发生碰撞

在掩码中加入任一头像碰撞层，即可通过射线检测直接检测头像：

* `ColliderLayer.CL_PLAYER`：匹配任意头像，包括本地玩家和场景中渲染的其他玩家。
* `ColliderLayer.CL_MAIN_PLAYER`：仅匹配本地（主）玩家。

这两个层可以组合使用，也可以单独使用。射线检测的默认 `collisionMask` 是 `CL_PHYSICS`，不会命中头像——你必须明确选择启用头像检测。

```ts
// 仅命中本地玩家（忽略其他头像）
raycastSystem.registerLocalDirectionRaycast(
  {
    entity: myEntity,
    opts: {
      direction: Vector3.Forward(),
      collisionMask: ColliderLayer.CL_MAIN_PLAYER,
    },
  },
  (raycastResult) => {
    if (raycastResult.hits.length > 0) {
      console.log('Hit the local player')
    }
  }
)

// 命中任意头像（本地 + 远程）
raycastSystem.registerLocalDirectionRaycast(
  {
    entity: myEntity,
    opts: {
      direction: Vector3.Forward(),
      collisionMask: ColliderLayer.CL_PLAYER,
    },
  },
  (raycastResult) => {
    // raycastResult.hits[i].entityId 对于远程头像命中结果为 0（没有场景本地实体 ID）
    console.log(raycastResult.hits)
  }
)
```

射线检测命中本地玩家时， `hit.entityId` 为 `engine.PlayerEntity`。命中远程头像时不会携带场景本地实体 ID（该字段为 `0`），因为远程玩家不是你场景世界中的实体。不过，命中结果仍会包含其 `position`, `length`, `normalHit`等几何数据。

{% hint style="info" %}
**💡 提示**：若要仅检测 **其他** 玩家（排除本地玩家），请使用 `CL_PLAYER` ，并在回调中筛选 `hit.entityId !== engine.PlayerEntity` 。
{% endhint %}

## 从玩家发出的射线检测

要从玩家的位置沿相机朝向发射射线，可以使用相机或化身作为射线起点进行射线检测 [保留实体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/entities-components.md#reserved-entities).

{% hint style="info" %}
**💡 提示**：在大多数情况下，你可能更适合使用 [指针事件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/click-events.md) ，而不是射线检测。
{% endhint %}

以下示例使用 `engine.CameraEntity` 实体，从玩家相机的位置向前发射射线。

```ts
raycastSystem.registerGlobalDirectionRaycast(
  {
    entity: engine.CameraEntity,
    opts: {
      queryType: RaycastQueryType.RQT_HIT_FIRST,
      direction: Vector3.rotate(
        Vector3.Forward(),
        Transform.get(engine.CameraEntity).rotation
      ),
    },
  },
  function (raycastResult) {
    console.log(raycastResult)
  }
)
```

{% hint style="warning" %}
**📔 注意**：请注意，在第三人称视角下，光标未来的行为可能与第一人称视角下不同。建议仅在玩家处于第一人称视角时使用此功能。
{% endhint %}

## 从光标位置进行射线检测

你也可以从玩家的光标位置向 3D 世界发射射线。此功能可用于拖动对象、射击游戏等场景。

在此示例中，我们检测玩家按下 E 键的操作，然后从光标位置向 3D 世界发射射线。接着，我们检查射线是否击中了某个实体；如果击中，就对该实体执行相应操作。

```ts
import { engine, Entity, InputAction, inputSystem, PointerEventType, RaycastQueryType, raycastSystem, TextShape, Transform } from '@dcl/sdk/ecs'
import { PrimaryPointerInfo } from '@dcl/sdk/ecs'

let cooldown = 1
let rayFrequency = 0.1
let mousePressed = false

export function main() {
   engine.addSystem(rayCastSystem)
}

const rayCastSystem = (t: number) => {

    if (inputSystem.isTriggered(InputAction.IA_PRIMARY, PointerEventType.PET_DOWN)) {
      mousePressed = true
    }

    if (inputSystem.isTriggered(InputAction.IA_PRIMARY, PointerEventType.PET_UP)) {
      mousePressed = false
    }

    if (!mousePressed) {
      cooldown = 0
      raycastSystem.removeRaycasterEntity(engine.CameraEntity)
      return
    }

    cooldown += t
    if (cooldown < rayFrequency) return
    cooldown = 0

    const pointerInfo = PrimaryPointerInfo.getOrCreateMutable(engine.RootEntity)
    let dir = pointerInfo.worldRayDirection

    raycastSystem.registerGlobalDirectionRaycast(
      {
        entity: engine.CameraEntity,
        opts: {
          queryType: RaycastQueryType.RQT_HIT_FIRST,
          direction: dir,
        },
      },
      function (raycastResult) {
        let result = raycastResult.hits[0]

        // 在命中位置执行相应操作
        if (result && result.position) {
          console.log("x:", result.position.x, ", y:", result.position.y, ", z:", result.position.z)
        }

        // 对命中的实体执行相应操作
        const entity = result.entityId as Entity
        if (entity) {
          console.log("entity: ", entity)
        }
      }
    )
}

```

{% hint style="info" %}
**💡 提示**：在此示例中，我们使用主按钮（E）触发射线检测。我们没有使用指针按钮（鼠标左键），因为默认情况下，单击并拖动也会改变相机角度。如果你想在拖动时避免旋转相机，可以使用 [虚拟相机](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/camera.md) 以将摄像机角度设为固定值。
{% endhint %}

## 高级语法

### 创建射线投射组件

Raycast 组件用于描述一条不可见射线，用来查询与其相交的实体。射线从实体的位置开始发射，该位置由 Transform 组件定义，并会受到所有父级实体变换的影响。方向可以通过多种方式定义，

射线使用以下数据定义：

* `direction`：一个包含 `$case` 字段的对象，该字段用于选择方向类型；对象还包含一个取决于该类型的附加字段，用于确定方向。以下是可接受的 `$case`:
  * `'localDirection'`：相对于实体朝前方向的方向，也会受到所有父级实体变换的影响。此方式适用于检测车辆前方的障碍物，并遵循车辆的朝向。旋转由 `localDirection` 字段定义，其值为一个 `Vector3` ，用于描述旋转。
  * `'globalDirection'`：忽略实体的旋转，将方向设为实体旋转为 0 时所朝向的方向。例如，这适用于始终朝下的情况。旋转由 `globalDirection` 字段定义，其值为一个 `Vector3` ，用于描述旋转。
  * `'globalTarget'`：在实体位置与场景中的全局目标位置之间发射一条射线。忽略实体的旋转。此方式适用于创建塔防游戏，例如让每座塔的炮塔瞄准空间中的一个精确坐标。目标由 `globalTarget` 字段定义，其值为一个 `Vector3` ，用于描述全局位置。
  * `'targetEntity'`：在实体位置与另一个目标实体的位置之间发射一条射线。忽略这两个实体的旋转。目标由 `targetEntity` 字段定义，其中保存对该实体的引用。
* `maxDistance`: *数字* 用于设置射线的发射长度。
* `queryType`: *RaycastQueryType* 枚举值，用于指定射线返回所有命中的实体，还是仅返回第一个命中的实体。可选项如下：
  * `RaycastQueryType.RQT_HIT_FIRST`：仅返回从射线起点开始遇到的第一个被击中的实体。
  * `RaycastQueryType.RQT_QUERY_ALL`：返回所有命中的实体，范围从起点直到射线的最大距离。
* `collisionMask`：仅检测特定碰撞层上的碰撞。可将其与自定义碰撞层搭配使用，也可用于仅检测物理层或指针事件层。请参阅 [碰撞层](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md#collision-layers)。默认值为 `ColliderLayer.CL_POINTER | ColliderLayer.CL_PHYSICS`.
* `originOffset`：不从实体的原点位置开始射线投射，而是添加一个偏移量，从相对位置开始查询。例如，可以使用较小的偏移量，防止射线与实体自身的 3D 模型发生碰撞。
* `continuous`：如果为 true，则每帧都会持续执行射线投射查询。如果为 false，则射线只在当前帧使用。默认值为 false。

{% hint style="warning" %}
**📔 注意**： `continuous` 属性应谨慎使用，因为每帧都运行一次射线检测查询会严重影响性能。尽可能使用一个系统（或 Utils 库中的 `interval` 函数）以更稀疏的固定间隔运行射线检测查询，参见 [重复射线检测](#recurrent-raycasting).
{% endhint %}

以下示例使用全局旋转来确定方向，并且仅返回射线发射所在帧中第一个被击中的实体。

```typescript
const entity1 = engine.addEntity()

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

Raycast.createOrReplace(entity1, {
  方向：{
    $case: "globalDirection",
    globalDirection: Vector3.create(0, 0, 1)
  },
  maxDistance: 16,
  queryType: RaycastQueryType.RQT_HIT_FIRST
})
```

下面的示例会沿实体的正前方发射射线，并且只返回命中的第一个对象。射线会持续发射。示例还包含 0.5 的轻微偏移，以防射线命中实体自身的碰撞体。

```typescript
const entity1 = engine.addEntity()

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

Raycast.createOrReplace(entity1, {
  方向：{
    $case: "localDirection",
    localDirection: Vector3.Forward()
  },
  maxDistance: 16,
  queryType: RaycastQueryType.RQT_HIT_FIRST,
  originOffset: Vector3.create(0.5, 0, 0),
  continuous: true
})
```

此示例会在两个实体之间追踪一条射线，并返回沿途命中的所有实体。

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

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

const entity2 = engine.addEntity()

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

Raycast.createOrReplace(entity1, {
  方向：{
    $case: "targetEntity",
    targetEntity: entity2
  },
  maxDistance: 16,
  queryType: RaycastQueryType.RQT_QUERY_ALL
})
```

### Raycast 结果组件

{% hint style="warning" %}
**📔 注意**：处理射线检测结果最简单的方法是使用 `raycastSystem`，并在创建射线的同一语句中注册回调函数。`RaycastResult` 组件由该接口在内部使用，同时也会公开，以便实现更高级的自定义逻辑。
{% endhint %}

创建 Raycast 组件后，添加此组件的实体将拥有一个 `RaycastResult` 组件。此组件包含射线命中信息。设置一个系统来检查这些数据。

&#x20;`RaycastResult` 组件包含以下数据：

* `globalOrigin`：射线的起始位置，以场景为参照。
* `direction`：射线所指向的全局方向，表示为一个 `Vector3`.
* `hits`：包含一个数组，每个被命中的实体对应一个对象。如果没有命中任何实体，此数组为空。如果射线检测使用了 `RaycastQueryType.RQT_HIT_FIRST`，此数组将只包含一个对象。

hits `hits` 数组中的每个对象都包含：

* `entityId`：被射线命中的实体的 ID 编号。
* `meshName`: *字符串* 其中包含 3D 模型中被命中的特定网格的内部名称。这在 3D 模型由多个网格组成时很有用。
* `position`: *Vector3* 表示射线与被命中实体相交的位置（相对于场景）
* `length`：射线从起点到与实体发生碰撞位置的长度。
* `normalHit`: *Vector3* 表示命中表面在世界坐标系中的法线。
* `globalOrigin`: *Vector3* 表示射线的起点位置（相对于场景）
* `direction`：射线所指向的全局方向，表示为一个 `Vector3`.

以下示例展示如何使用系统访问单个实体的结果：

```typescript

const rayEntity = engine.addEntity()

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

// 返回所有实体
Raycast.createOrReplace(rayEntity, {
  方向：{
    $case: "globalDirection",
    globalDirection: Vector3.create(0, 0, 1)
  },
  maxDistance: 16,
  queryType: RaycastQueryType.RQT_QUERY_ALL
})

engine.addSystem(() => {
  const rayResult = RaycastResult.get(rayEntity)
  console.log(rayResult.hits)
})
```

下一个示例展示如何使用 `RaycastResult` 组件查询来访问场景中所有实体的 [组件查询](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jia-gou/querying-components.md).

```typescript
engine.addSystem(() => {
  for (const [_, result] of engine.getEntitiesWith(RaycastResult)) {
    console.log(result.hits)
  }
})
```

{% hint style="warning" %}
**📔 注意**：射线检测结果不会在创建射线检测的同一个游戏循环刻中返回。结果可能需要一个或多个刻才能返回。
{% endhint %}

在使用多种射线执行不同任务（例如寻路、视线检测、弹道追踪等）的场景中，你可能需要使用不同的 [碰撞层](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/colliders.md#collision-layers)，以避免计算无关的碰撞。

{% hint style="info" %}
**💡 提示**：射线检测的可运行示例，请参阅 [`77,-1-raycast-unit-tests`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/77,-1-raycast-unit-tests) 测试场景，用于断言通过 `@dcl/sdk/testing` 针对以下各项的单元测试： `localDirection`, `globalDirection`, `globalTarget` 和 `targetEntity` 方向形式（包括从经过变换的父级发出的射线）。如需了解射线可命中的碰撞体层的行为，请参阅 [`5,5-collider-layers`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/5,5-collider-layers).
{% 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/jiao-hu-xing/raycasting.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.
