跳转到内容

glTF模型

相关参考:

Web 插件对 glTF/GLB 模型的支持,主要体现在“动态创建模型”和“控制模型动画”两个方向。

创建模型

使用 URL

js
const model = await api.createGltfModel('https://your.domain.com/model/rabbit.glb');
await api.add(model);

使用 ArrayBuffer

js
const response = await fetch('/my-assets/model/rabbit.glb');
const buffer = await response.arrayBuffer();

const model = await api.createGltfModel(buffer);
await api.add(model);

如果使用 URL,请确保资源服务器对 https://www.kivicube.com 开放 CORS。

模型是最常见的“组合对象”

glTF 模型通常不是一个单独对象,而是一棵对象树。因此常见用法是:

js
const model = await api.getObject('rabbit');
const children = await api.getChildren(model);

如果你需要控制模型内部某个节点,可以结合 getChildByProperty() 查找。

基础操作

js
await api.setPosition(model, 0, 0, 0);
await api.setRotation(model, 0, Math.PI / 2, 0);
await api.setScale(model, 1.5, 1.5, 1.5);

动画控制

读取动画名

js
const names = await api.getAnimationNames(model);
console.log(names);

播放动画

js
await api.playAnimation(model, {
  name: 'Idle',
  loop: true,
  repeat: Infinity,
});

动画配置还支持:

  • loop - 是否循环播放
  • repeat - 循环次数
  • repeatMode - 循环模式。0:正常, 1: 往复
  • timeScale - 播放倍速。1为原始速度。默认为1
  • weight - 多动画播放时的权重占比。默认为1
  • clampWhenFinished - 播放完毕后,是否停留最后一帧。
  • resetLoopCount - 重置循环播放的次数为0

暂停、停止、重播

js
await api.pauseAnimation(model, 'Idle');
await api.stopAnimation(model, 'Idle');
// 支持的参数和playAnimation一致。
await api.playbackAnimation(model, { name: 'Idle', loop: true });

读取状态

js
const running = await api.animationIsRunning(model, 'Idle');
const loop = await api.isAnimationLoop(model, 'Idle');
const runningNames = await api.getAnimationIsRunningNames(model);

动画事件

js
const obj = await api.getObject('rabbit');
  • play - 动画播放时触发
js
function onPlay(event) {
  // animationName - 当前播放的动画名称
  const { type, target, animationName } = event;
}

await api.on('play', onPlay, obj);
  • pause - 动画暂停时触发
js
function onPause(event) {
  // animationName - 当前暂停的动画名称
  const { type, target, animationName } = event;
}

await api.on('pause', onPause, obj);
  • ended - 动画自然播放完毕时触发
js
function onEnded(event) {
  // animationName - 当前播放完毕的动画名称
  const { type, target, animationName } = event;
}

await api.on('ended', onEnded, obj);
  • replay - 动画重新播放时触发
js
function onReplay(event) {
  // animationName - 当前重新播放的动画名称
  const { type, target, animationName } = event;
}

await api.on('replay', onReplay, obj);

自定义动画,和模型内置动画,在事件和控制上是同样的支持。

灯光与环境贴图

模型往往是最需要配合灯光、环境贴图一起使用的对象。常见组合是:

  1. 创建模型
  2. 添加到场景
  3. 设置位置/缩放
  4. 调整环境贴图和色调映射
  5. 再微调默认灯光

相关能力见: