三.js 单击时获取相对于此值的对象(对象都在数组中)
three.js Get objects relative this value on click (objects are all in an array)
问题
好的,所以我对three.js
相对较新,我正在尝试这样做:在 3D 空间中单击头像时,它会相对于此值抓取选定的头像(所以我可以做 returned_object.position.x 和 returned_object.data.name 等),但它不起作用。 现在我可以单击一个对象,它会显示该对象的three.js
SCENE 值,但不是我的。
-- 编辑添加内容
我希望能够获取头像功能设置的this.data
值 - 点击头像。
但是当我console.log(intersects);
代码中如下所示时,它会提出三个对象.js东西。 有关屏幕截图,请参阅此链接
我只想做一些类似console.log(intersects.data);
的事情,让它返回头像函数中设置的内容
对不起,这很难用语言表达。
《守则》
以下是理解这一切所需的所有代码:
var avatars = [],
avatar;
avatar = function(id, row) {
this.data = row;
this.avatar = new THREE.Object3D();
this.avatar.add(head);
this.avatar.position.x = 20 * id;
//extra
SCENE.add(this.avatar);
avatars[id] = this;
}
$(document).click(function(event){
// calculate mouse position in normalized device coordinates
// (-1 to +1) for both components
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
mouse.fx = -mouse.y / 6;
mouse.fy = (mouse.x / 6) + 0.3;
CAMERA.rotation.x = ((-mouse.y) / 30) + -0.4;
CAMERA.position.z = (mouse.y * -20) + 80;
CAMERA.position.x = (mouse.x * 20);
raycaster.setFromCamera( mouse, CAMERA );
var intersects = raycaster.intersectObjects( SCENE.children, true ); // It grabs all the objects in the scene, but I only need it to grab objects in the avatars array.
console.log(intersects);
//I want to just do - console.log(intersects.data); - and have it return what is set in the avatar function.
console.log(intersects);
});
现在我明白了:你的头像由一个或几个物体组成,当然这些物体是由光线投射器返回的,但感兴趣的数据在你的头像数组中。
你可以用任何一种方式来做:每个Object3D
都有一个userData
对象,你可以在其中放置你的数据(this.avatar.userData = row;
)。由于相交对象是(在本例中)头像,它是头像的子对象,因此您可以通过intersects[0].object.parent.userData
访问数据。
也许更好的方法是在该userData
对象中仅存储 id。因为有了id,你就有了对头像数组的"引用"。
// save id to userData
this.avatar.userData.id = id;
// accessing avatar
var clickedAvatar = avatars[intersects[0].object.parent.userData.id];
console.log(clickedAvatar.data.name);
相关文章:
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 在Javascript中转换对象数组
- 在JavaScript中通过索引从对象数组中获取值
- Backbone虹吸以获取对象数组
- 如何在DataTables 2.1中迭代对象数组
- Javascript-根据赋值顺序,按键合并对象数组
- 将事件附加到对象/数组
- jQuery$.inArray()总是返回-1和一个对象数组
- javascript处理一个对象数组以获得一个新的对象数组
- javascript在数组中获取对象数组中键的所有不同值
- 在对象数组中查找多个值的d3范围
- Undercore.js获取对象数组中键对象的值
- 在mongoose中使用正则表达式在对象数组中进行查询搜索
- 如何通过json对象数组为嵌套对象赋值
- 如何循环通过2个对象数组并通过匹配id进行合并
- 为对象数组创建列表项
- 如何使用javascript合并两个对象数组
- JSON到对象数组,并向每个对象添加项
- JavaScript:从对象数组中获取唯一值及其计数
- 按不同项目对对象数组进行排序