javascript - 在 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
}
}
希望有人可以帮忙。
解决方案
我已经编辑了您的示例代码,以展示如何在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 答案应该更多地解释范围界定的差异。
希望这会有所帮助!让我知道是否有任何不清楚的地方。
推荐阅读
- wordpress - Wordpress TinyMCE 问题 - 编辑器选项卡不显示
- azure - 按标记的 Azure 资源组
- excel - 将数据标签添加到 Excel 图表 - 耗时
- gitignore - printf 换行符忽略文件
- python - 现有连接阻止我使用 python 发送电子邮件
- androidappsonchromeos - 为什么新活动会在 ChromeOS 上创建新 Windows?如何将它们限制在一个窗口中?
- python - 使用内连接将 SQL 转换为 Django orm
- css - 我怎样才能让一个 div 增加高度,而不是先跳到我的左浮动 div 下面然后增加高度?
- typescript - Nativescript 使用动态参数调用全局转换器
- excel - 如何格式化表格中的一行而不是工作表上的整行?