Spark AR ——动态实例化(四)【脚本】

275 阅读2分钟

本文已参与掘金创作者训练营第三期「高产更文」赛道,详情查看:掘力计划|创作者训练营第三期正在进行,「写」出个人影响力

Spark AR 是 Facebook 免费创作 AR 作品的平台,使用户能够为 Facebook 和 Instagram 创建交互式增强现实体验,超过 40 万名创作者,190个国家/地区,使用 Spark AR 来创作自己的AR作品

由于该软件无需任何编码知识即可使用,因此任何人现在都可以在 AR 世界中几乎没有经验地制作下一个疯狂式传播的 Instagram AR 特效,引领世界潮流。

专门的 AR 滤镜设计师单价甚至可达到 1000 美元到 3 万美元不等。

调整对象的父对象(重新排序)

动态实例化的对象可以在运行时通过使用 SceneModuleSceneObjectBase API 公开的 addChild()removecchild()removeFromParent() 方法被重新调整父对象。

在场景面板中没有父对象的动态对象将不会被渲染,直到它们被添加回场景中对象的子对象。

从父对象中删除动态对象并不会自动处理它。动态对象的销毁必须通过显式调用 destroy() 方法来执行。

在下面的例子中,在场景面板中,当平面被轻击时,平面在两个组之间被重新调整父对象。当平面被长时间按压时,动态平面将从其父平面中移除,而不管它是在两组中的哪一组之下。

// Load in the required modules
const Scene = require('Scene');
              
// Enable the Touch Gestures > Tap Gesture capability 
// in the project's properties
const TouchGestures = require('TouchGestures');

// Enables async/await in JS [part 1]
(async function() {

    // Locate the focal distant object in the Scene
    // Then dynamically instantiate two objects to use as groups and a plane
    const [focalDistance, groupOne, groupTwo, dynamicPlane] = await Promise.all([
        Scene.root.findFirst('Focal Distance'),

        Scene.create("SceneObject", {
            "name": "group0",
        }),

        Scene.create("SceneObject", {
            "name": "group1",
        }),

        Scene.create("Plane", {
            "name": "Dynamic Plane",
            "width": 0.1,
            "height": 0.1,
            "y": -0.2,
            "hidden": false,
        }),
    ]);


    // Add the groups as children of the Focal Distance object in the Scene panel, then add the plane as a child of the first group
    focalDistance.addChild(groupOne);
    focalDistance.addChild(groupTwo);
    groupOne.addChild(dynamicPlane);


    // Create a variable to track which of the two groups the plane belongs to
    let isAChildOfGroupOne = true;

    // Reparent the dynamic plane between the two groups when the plane is tapped
    TouchGestures.onTap(dynamicPlane).subscribe(() => {
        if(isAChildOfGroupOne){
            groupTwo.addChild(dynamicPlane);
            isAChildOfGroupOne = false;
        } else {
            groupOne.addChild(dynamicPlane);
            isAChildOfGroupOne = true;
        }
    });
    
    // Remove the dynamic plane from its parent when the plane is long pressed
    TouchGestures.onLongPress(dynamicPlane).subscribe(() => {
        dynamicPlane.removeFromParent();
    });
              
// Enables async/await in JS [part 2]
})();