gpt4 book ai didi

javascript - three.js 在点击时获取相对于此值的对象(对象都在一个数组中)

转载 作者:行者123 更新时间:2023-11-30 16:18:47 24 4
gpt4 key购买 nike

问题

好的,所以我对 three.js 比较陌生,我正在尝试这样做:在 3D 空间中点击一个头像,它会抓取与该值相关的所选头像(所以我可以做 returned_object.position.x 和 returned_object.data.name 等...)但它不起作用。现在我可以单击一个对象,它会显示该对象的 three.js SCENE 值,但不是我的。

-- 编辑添加

我希望能够在点击头像时获取头像功能设置的 this.data 的值。
但是当我 console.log(intersects); 如下代码所示时,它出现了 three.js 对象,stuff。 See this link for a screenshot

我只想做类似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);


});

最佳答案

现在我明白了:您的化身由一个头部或多个对象组成,当然这些对象由 raycaster 返回,但感兴趣的数据在您的化身数组中。

您可以采用任何一种方式:每个 Object3D 都有一个 userData 对象,您可以在其中放置数据 (this.avatar.userData = row;)。由于相交对象(在本例中)是头像的子对象头部,因此您可以通过 intersects[0].object.parent.userData 访问数据。

也许更好的方法是只将 id 存储在 userData 对象中。因为有了 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 - three.js 在点击时获取相对于此值的对象(对象都在一个数组中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35067691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com