我正在尝试使用 lance-gg 库编写游戏。
我尝试实现一个简单的 aframe 组件,用于打印实体在世界空间中的 object3D 位置和旋转。
问题是我无法从组件事件监听器中访问 this
。
我尝试四处搜索,找到了这个[线程]( Aframe unregister component ),所以我猜问题是初始化顺序。我尝试直接从索引包含一个组件,但它也不起作用。
// aSeparateFile.js
AFRAME.registerComponent(
'custom-component',
{
schema: {
controllerID: {
type: 'string',
default: 'none'
}
},
init: () => {
console.log('componet has been created');
console.log(this);
},
tick: () => {
console.log(this.el.object3D.rotation);
console.log(this.el.object3D.position);
}
}
);
此组件是在名为 aSeparateFile.js
的单独文件中创建的,我从 AFrameRenderer 扩展中包含此文件。像这样:
import {AFRAMERenderer} from 'lance-gg';
import './aSeparateFile.js';
我想知道使用 lance-gg 注册自定义组件的最佳方法。
最佳答案
不要使用arrow functions这会将方法绑定(bind)到错误的 this
。使用常规函数代替:
AFRAME.registerComponent(
'custom-component',
{
schema: {
controllerID: {
type: 'string',
default: 'none'
}
},
init: function () {
console.log('componet has been created');
console.log(this);
},
tick: function () {
console.log(this.el.object3D.rotation);
console.log(this.el.object3D.position);
}
});
关于javascript - Aframe 组件无法从事件处理程序引用 el,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58421696/