Interactable elements on a spherical map in three.js

I've been trying to implement raycasting to make objects clickable. Despite referencing numerous examples, the code doesn't seem to work for me. The only notable difference is that I'm working within a sphere.

My initial setup involves defining various variables (some may not be directly related to previous attempts).

 var container, stats;
 var camera, controls, scene, renderer, projector;
 var isUserInteracting = false;
 var mouse = { x: 0, y: 0, z: 0 }, intersected;




  var fov = 70,
  texture_placeholder,
  isUserInteracting = false,
  onMouseDownMouseX = 0, onMouseDownMouseY = 0,
  lon = 0, onMouseDownLon = 0,
  lat = 0, onMouseDownLat = 0,
  phi = 0, theta = 0;

  init();
  animate();

The next step involves setting up the init() function where I configure the camera and create a spherical mesh.

        function init() {

            var container, mesh1;



            container = document.getElementById( 'container' );

            camera = new THREE.PerspectiveCamera( fov, window.innerWidth / window.innerHeight, 1, 1100 );
            camera.target = new THREE.Vector3( 0, 0, 0 );

            scene = new THREE.Scene();

            projector = new THREE.Projector();

            mesh1 = new THREE.Mesh( new THREE.SphereGeometry( 500, 60, 40 ), new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( "spherical_map_small.jpg" )} ) );
            mesh1.scale.x = -1;
            mesh1.side = THREE.DoubleSide;
            scene.add( mesh1 );

Within the init() function, I proceed to create a cube geometry (the object intended to be clickable).

meshMaterial = new THREE.MeshBasicMaterial({ color: 0x33CC00});

            var geometry = new THREE.CubeGeometry( 20, 20, 20 );

            var object = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { color: 0x33CC00} ) );
            object.position.x = 75;
            object.position.y = 10;
            object.position.z = 0;

            object.rotation.y = 45;

            scene.add( object );

            objects.push( object ); 

Still within init(), I set up the renderer and add event listeners.

            renderer = new THREE.WebGLRenderer();

            renderer.setSize( window.innerWidth, window.innerHeight );

            container.appendChild( renderer.domElement );

            document.addEventListener( 'mousedown', onDocumentMouseDown, false );
            document.addEventListener( 'mousemove', onDocumentMouseMove, false );
            document.addEventListener( 'mouseup', onDocumentMouseUp, false );
            document.addEventListener( 'mousewheel', onDocumentMouseWheel, false );
            document.addEventListener( 'DOMMouseScroll', onDocumentMouseWheel, false);

            //

            window.addEventListener( 'resize', onWindowResize, false );

Now comes the challenge. The following function should make my box 'object' clickable, but it's not functioning as expected. I expect it to display "works." every time an object in the scene is clicked.

Despite spending hours learning about raycasting in three.js, I can't seem to figure out why it's not working. Any assistance would be greatly appreciated. Thank you.

Answer №1

Consider this idea: why not give this a try?

raycaster.intersectObjects(scene.children, true);

Make sure to set recursive as true. If not, it won't check the children elements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that you do not proceed with the next step until the promise has been fulfilled

I am currently faced with a challenge in my project where I have a service that wraps a 3rd-party API to retrieve data into my controller. However, I need to perform some data processing to pivot the information before displaying it, but I am struggling to ...

"Looking to create a voting button similar to Stackoverflow's up-down feature? Let's explore how you

Challenges to Overcome What is the best approach for creating Ajax buttons (upward and downward arrows) that allow users to increase or decrease a number? How can user actions be stored in a variable called NumberOfVotesOfQuestionID? I am undecided on w ...

Incorporate new content into a jquery mobile listview on the fly

I'm attempting to use JavaScript to dynamically populate a listview with items. Here is the code I have written: //Function to load data fields for items dynamically function initialiseFields(listViewId){ for(var i = 0; i < 10; i++){ ...

Troubleshooting a JavaScript project involving arrays: Let it pour!

I'm a beginner here and currently enrolled in the Khan Academy programming course, focusing on Javascript. I've hit a roadblock with a project called "Make it rain," where the task is to create raindrops falling on a canvas and resetting back at ...

First, the image is reduced by width until it reaches its maximum width, then the height is adjusted proportion

I have an image with the dimensions of 1200 x 200px. In the center of this image, there is a space measuring 500 x 200px which represents the main content of the entire image. Flanking this main content are additional contents on each side. It is important ...

Show or hide a specific element based on the property assigned to a user's role

In my current project, I am focusing on distinguishing between two key user roles: editor and guest. The editor holds complete privileges for create, read, update, and delete operations, while the guest is limited to viewing certain elements like a list ...

Error: Angular does not recognize x2js XML format

I'm attempting to adapt this particular example to utilize xml as json data. However, I am encountering some issues with the code. courses = x2js.xml_str2json(data); console.log(courses.books.course); $scope.todos = courses.books.course; In the XML ...

Identify specific terms within a webpage using an iframe that is integrated onto the same page

Is there a way to implement word highlighting on a webpage containing an iframe with a search field? The concept involves allowing a user to input search terms within the iframe, which would then send a command to highlight those words on the main page. ...

Stopping the Bootstrap carousel when an input is focused

I have a Bootstrap carousel with a form inside. The carousel is set to pause when hovered over, but I noticed that if the cursor leaves the carousel while typing in the inputs, it goes back to its default cycle of 5000ms. I want the carousel to remain pau ...

Updating the value of a rails parameter with JavaScript

I am trying to enhance my search form by pre-populating the fields with the "last searched values" when a user submits a search. The search form and results are displayed on the same page, and if there is no previous search, the fields should show placehol ...

Using Javascript to organize data in a table

I have a basic HTML table setup that looks like this: <table id="myTable"> <thead> <tr> <th class="pointer" onClick="sortTable()">Number</th> <th>Example3</th> <th ...

Performing a fetch() POST request in Express.js results in an empty body object being generated

Purpose: Implement a function in fetch() to send specified string data from the HTML document, for example "MY DATA" Here is the code snippet: HTML Code: <!DOCTYPE html> <html> <body> <script type="text/javascript"> function ...

Issue encountered while trying to load electron-tabs module and unable to generate tabs within electron framework

I've recently set up the electron-modules package in order to incorporate tabs within my Electron project. Below are snippets from the package.json, main.js, and index.html files. package.json { "name": "Backoffice", "version": "1.0.0", "descr ...

Angular 6: Issue with displaying data on the user interface

Hello! I am attempting to fetch and display a single data entry by ID from an API. Here is the current setup: API GET Method: app.get('/movies/:id', (req, res) => { const id = req.params.id; request('https://api.themoviedb.org/ ...

Mastering the art of manipulating the Document Object Model in Vue.js

I have a situation where I am using v-for to display a lot of data in JSON as individual buttons. My goal is to change the background color of the button when it is clicked. I plan to use @click to bind a function to each button, and within that function, ...

Transferring temporary information from server to controller using angular-file-upload

Currently, I am utilizing the angular-file-upload library which can be found at this link: https://github.com/danialfarid/angular-file-upload. In the example provided on that page, data from a file is sent to the backend from a controller using the availab ...

ExpressJS: utilizing middleware with regex

I'm facing an issue with routing using the regex matching feature in expressJS 4. I'm trying to utilize app.use() to specify which routes are accessible for URLs that do not begin with /api routesWebAuth.js var express = require('express& ...

creating a Vue app using Node results in an HTML page with no content due to syntax errors

After creating a VueJs page using the CLI, I wanted to share it with others who might not have Vue CLI or Node installed. Just like opening .html files in a browser, I tried to open the index.html file after building it. However, when I opened the file, a ...

A step-by-step guide on implementing the bliss view engine in Express.js instead of Jade

Is there a way to utilize the bliss view engine instead of the typical jade engine in Express JS? I came across an article on Stack Overflow, but it seems to be geared towards an older version of express.js. I am using version 3.x. Specifically, I am int ...

What is the best way to divide middleware within feathers?

I have been using the multer library with feathers to upload files. In my effort to separate logic from code, I have decided to move the upload functionality from the index.js file to a new file named pdf.js within the middleware directory. Below is the c ...