对象挂载管理
ObjectManagerScript(脚本变量 oms)负责在运行时调整场景对象的父子关系,常用于搬运、装配、拆解等场景。核心理念是:通过重新挂载来改变对象在层级中的位置,从而驱动显示和逻辑效果。
addToParent
addToParent({
childName: string;
parentName: string;
childPath?: string;
offset?: {x: number; y: number; z: number};
rotation?: {x: number; y: number; z: number};
ignoreParentScale?: boolean;
}): { success: boolean; error?: string };
childName:要挂载的对象。parentName:目标父节点。childPath:当父节点存在子路径时指定,如"Group/Sub"。offset、rotation:挂载后的初始偏移与旋转,单位分别为米和度。ignoreParentScale:为true时,忽略父节点缩放,保持子对象原尺寸。
示例:
oms.addToParent({
childName: 'item001',
parentName: 'carrier1',
offset: {x: 0, y: 0.45, z: 0},
});
removeFromParent
removeFromParent({childName: string}): { success: boolean; error?: string };
恢复对象到其原始父节点及姿态。常在卸货或拆卸流程后调用,以保持场景整洁。
场景应用建议
- 多层挂载:对复杂结构(如托盘 + 货箱 + 零件),建议自上而下分层挂载,记录每一步的原始位置,便于还原。
- 结合动画:在
addToParent前可使用gsap对child做一个平滑移动,使挂载过程更自然。 - 状态缓存:
后续变化时更新缓存,方便脚本重用。
const itemState = {
parent: 'carrier1',
offset: {x: 0, y: 0.45, z: 0},
};
oms.addToParent({childName: 'item001', parentName: itemState.parent, offset: itemState.offset});
常见问题
| 情况 | 说明 |
|---|---|
返回 error: child not found | 检查对象名称是否与场景一致,可通过 editor.getByName 验证。 |
| 挂载后偏移异常 | 可能是父节点本身带有旋转或缩放,尝试调整 offset、rotation 或设置 ignoreParentScale: false。 |
| 拆卸后仍跟随 | 若对象在物理引擎中存在约束,需同步移除对应的逻辑关系或重置脚本状态。 |
通过 oms 可以在不重新加载场景的情况下完成复杂的装配流程,是搭建互动演示的重要工具。