> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-embody/add-a-3d-character-to-a-three-js-scene.md).

# 向 three.js 场景添加 3D 角色

使用无需框架的 Convai Embody API，将 Convai 角色添加到现有的 3D 网页场景中，并在你自己的渲染循环中更新它。

无需 React，即可将 Convai 角色添加到已有的 three.js 场景中。如果应用自行管理渲染器、场景和摄像机，请使用本指南。完成后，角色将站在场景中，由渲染循环驱动，并能说话和同步唇形。

### 前提条件

* 一个包含渲染器、带灯光的场景、摄像机和渲染循环的 three.js 应用。
* Node.js 18 或更高版本，以及一个打包工具。
* Convai API 密钥或身份验证令牌，以及角色 ID。角色的虚拟形象需要有已发布的 Web 形体，或者适用的默认形体。

### 安装包

包  `@convai/embody`  的根入口既不导入 React，也不导入  `@react-three/fiber`，因此这种方式只需要两个必需的对等依赖。

```bash
npm install @convai/embody @convai/web-sdk three
```

### 创建角色

`createCharacter`  会解析并加载角色的形体，建立 Convai Web SDK 连接，然后返回一个句柄。将该句柄的  `root`  添加到场景中，并将摄像机赋给该句柄，以便角色的视线能够追踪摄像机。

{% code title="src/character.ts" %}

```typescript
import * as THREE from 'three'
import { createCharacter } from '@convai/embody'

export async function addCharacter(
  scene: THREE.Scene,
  camera: THREE.Camera,
  renderer: THREE.WebGLRenderer,
  token: string,
) {
  const character = await createCharacter({ token, characterId: 'YOUR_CHARACTER_ID' })

  scene.add(character.root)
  character.camera = camera

  const clock = new THREE.Clock()
  renderer.setAnimationLoop(() => {
    character.update(clock.getDelta())
    renderer.render(scene, camera)
  })

  return character
}
```

{% endcode %}

`update`  根据经过的秒数推进动画、唇形同步、视线、呼吸和眨眼。每帧渲染前调用一次。

如果角色启用了长期记忆，连接时还需要提供终端用户 ID，以便角色区分不同用户： `createCharacter({ token, characterId, session: { endUserId: user.id } })`。如果未提供，连接将失败并返回 "Missing end\_user\_id"。

{% hint style="warning" %}
如果没有设置  `character.camera`，视线追踪将不起作用，角色会直视前方。摄像机创建后，请设置该属性。
{% endhint %}

### 为角色设置灯光

角色会使用场景中已有的灯光。要获得类似工作室影片的人像效果， `createPortraitRig`  会返回  `ConvaiCharacter`  在其自身画布中使用的灯光配置（摄像机左侧 45° 处带柔和阴影的主光、冷色补光、暖色轮廓光和微弱的天空光），而  `placePortraitRig`  会在每一帧旋转该配置，使其跟随摄像机。 `PORTRAIT_TONE`  是与之匹配的色调映射。

{% code title="src/lights.ts" %}

```typescript
import * as THREE from 'three'
import { createPortraitRig, placePortraitRig, PORTRAIT_TONE } from '@convai/embody'

export function lightScene(scene: THREE.Scene, renderer: THREE.WebGLRenderer) {
  renderer.toneMapping = PORTRAIT_TONE.toneMapping
  renderer.toneMappingExposure = PORTRAIT_TONE.exposure
  renderer.shadowMap.enabled = true

  const rig = createPortraitRig()
  scene.add(rig.key, rig.key.target, rig.fill, rig.fill.target, rig.rim, rig.rim.target, rig.sky)

  // 每帧渲染前调用一次：相机绕行时，主光始终位于相机左侧。
  const face = new THREE.Vector3(0, 1.6, 0)
  return (camera: THREE.Camera) => placePortraitRig(rig, camera.position, face)
}
```

{% endcode %}

如果场景的灯光效果已经符合你的预期，可以跳过此步骤；角色的皮肤、头发、眼睛和牙齿经过着色处理，可适应各种灯光。

### 向角色发送消息

`character.client` 是 Convai Embody 打开的 Convai Web SDK `ConvaiClient` 。使用它进行对话。只有在角色使用 `null` 创建时，它才会是 `connect: false`.

```typescript
character.client?.sendUserTextMessage('Walk me through the lockout procedure.')
```

### 释放角色

在角色离开页面时调用 `dispose` 。此方法会释放模型及其材质和纹理、动画混合器，并关闭 Convai Embody 打开的连接。

```typescript
scene.remove(character.root)
character.dispose()
```

通过 `client` 选项传入的客户端会保持连接。其生命周期由你的应用负责管理。

### 验证角色

运行应用并发送一条消息。

{% hint style="success" %}
角色会播放待机动画，眼睛会跟随相机，嘴部会随语音回复同步动作。
{% endhint %}

如果 `createCharacter` 返回拒绝状态，请查看错误消息。React 指南的 [故障排除部分](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-embody/add-a-3d-character-to-a-react-app.md#troubleshooting) 介绍了相同的错误，因为这两种方式共用同一个加载器。

### 后续步骤

{% content-ref url="/pages/b60906ed5049da52cc6ddb85571a9101f1eacdb4" %}
[createCharacter 参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-embody/createcharacter-reference.md)
{% endcontent-ref %}

{% content-ref url="/pages/9dbcb19bcd28e49fb8d9a21383d0cb38608d1127" %}
[Convai Embody 的工作原理](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-embody/how-convai-embody-works.md)
{% endcontent-ref %}


---

# 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.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-embody/add-a-3d-character-to-a-three-js-scene.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.
