Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With three.js, can I attach information to an object, such as a URL?

Tags:

I have a webgl question related to three.js. I would like to attach information to an object. For instance, when I click on an object, I would like to retrieve some information that's tied to the object, like a URL, and then run a function using that information.

The code I'm using for finding the object is:

    var vector = new THREE.Vector3((event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1, 0.5);     projector.unprojectVector(vector, camera);      var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());      var intersects = raycaster.intersectObjects(objects);      intersects[0].object.material.color.setHex(Math.random() * 0xffffff); 

The last line being how I'm currently manipulating the object. The array objects is simply an array of all of the objects. The issue is I don't know enough about how Raycaster or intersectObjects works, or enough about how to tie any information to an object so it can be recalled later.

like image 961
JVE999 Avatar asked Aug 19 '13 16:08

JVE999


People also ask

What three Js can do?

Three. js is a powerful library for creating three-dimensional models and games. With just a few lines of JavaScript, you can create anything from simple 3D patterns to photorealistic, real-time scenes. You can build simple and complex 3D geometrics, animate and move objects through a lifelike scene, and more.

How does Raycaster work in 3 js?

Raycasting means throwing a ray from the mouse position on the screen to the scene, this is how threejs determines what object you want to click on if you have implemented it.


1 Answers

indeed you can set custom user data to an object in Three.js. The key here is the Object3D which is the basis for all scene graph objects. The docs have a property called

Object3D.userData;  

This can be loaded with an object of your choice and when the Raycaster class retrieves your intersect you can simply access it directly at that point.

Setter during init or runtime

Object3D.userData = { URL: "http://myurl.com" }; 

Getter on Collision

window.location = intersects[0].object.userData.URL; 
like image 90
Darryl_Lehmann Avatar answered Oct 06 '22 01:10

Darryl_Lehmann