首页 > 解决方案 > 在 ThreeJS 中随时间改变 Collade 对象的位置

问题描述

我正在使用精灵示例,它是ThreeJS的标准示例

我想在 x 和 y 方向上移动对象,而不是示例中显示的旋转。这应该可以通过更改init() 函数elf.position.x来实现。elf.position.y

我面临的这个问题是我创建了一个创建精灵的方法的对象(类),因此我可以创建多个。我还有一个应该随着时间移动对象的功能。var e在移动功能中无法访问。当我将其更改为this.e并将其更改为时e = collada.scene;this.e = collada.scene;我收到以下错误:Uncaught TypeError: Cannot set property 'e' of undefined

代码:

 class DrawElf {
    constructor(scene) {
        var e;
        this.loadingManager = {};
        this.loader = {};
        this.scene = scene;

        // loading manager
        this.loadingManager = new THREE.LoadingManager(function () {
            scene.add(e);
        });

        // collada
        this.loader = new THREE.ColladaLoader(this.loadingManager);
        this.loader.load('./models/collada/elf/elf.dae', function (collada) {
            e = collada.scene;
            e.scale.set(30, 30, 30);
            e.position.set(100, 10, 100);
            e.name = "elf.dae" + 0 + 0;

            e.traverse(function (child) {
                if (child instanceof THREE.Mesh) {
                    child.name = e.name;
                    ToIntersect.push(child);
                }
            });
        });
    }

    move(time) {
        // i want to move the object
    }
}

希望有人可以帮忙。

标签: javascriptthree.jsloadercollada

解决方案


我已经编辑了您的示例代码,以展示如何在move()函数中访问 elf 模型,并在下面的注释中标注了更改。

class DrawElf {
    constructor(scene) {

        // Change 1: Place the `e` variable on `this` so it's accessible
        // from member functions like `move`
        this.e = null;
        this.loadingManager = {};
        this.loader = {};
        this.scene = scene;

        // Change 2: Use arrow functions instead so that the scope of the
        // constructor is retained in the callback and `this` still references
        // the new `DrawElf` instance 
        // collada
        this.loader = new THREE.ColladaLoader();
        this.loader.load('./models/collada/elf/elf.dae', (collada) => {
            this.e = collada.scene;
            this.e.scale.set(30, 30, 30);
            this.e.position.set(100, 10, 100);
            this.e.name = "elf.dae" + 0 + 0;

            this.e.traverse(function (child) {
                if (child instanceof THREE.Mesh) {
                    child.name = this.e.name;
                    ToIntersect.push(child);
                }
            });


            // Change 3: Remove the loading manager because it's not needed to
            // add the elf to the scene and instead do so here
            scene.add(this.e);
        });
    }

    move(time) {
        // Change 4: Check if the scene has been loaded before trying to move
        // the model
        if (this.e) {
            // move the model here
        }
    }
}

这里最大的变化是使用箭头函数而不是原始的 Javascript 函数,因此this仍然引用正在构造的对象实例。这个 SO 答案应该更多地解释范围界定的差异。

希望这会有所帮助!让我知道是否有任何不清楚的地方。


推荐阅读