三.js 单击时获取相对于此值的对象(对象都在数组中)

three.js Get objects relative this value on click (objects are all in an array)

本文关键字:对象 数组 单击 js 获取 相对于      更新时间:2023-09-26

问题

好的,所以我对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);