Guide to selectively hovering over a single object with raycasting

I'm encountering an issue with my code that handles object "hovering". The problem arises when multiple objects overlap and can be hovered over simultaneously if the meshes intersect at the mouse point. Although I know that the intersections array is sorted to prioritize the closest element, I'm struggling to leverage this in my current code implementation. Any insights or suggestions would be greatly appreciated.

Check out a live demo along with the code snippet:

import * as THREE from 'three';
import { OrbitControls } from 'three-controls';

// ----------------------- SCENE
const scene = new THREE.Scene();

// ----------------------- CAMERA
const camera = new THREE.PerspectiveCamera(
  60,
  window.innerWidth / window.innerHeight,
  0.1,
  10000
);
camera.position.set(0, 0, 5);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xfff000);
document.body.appendChild(renderer.domElement);
renderer.setPixelRatio(window.devicePixelRatio);

// ----------------------- CONTROLS
const controls = new OrbitControls(camera, renderer.domElement);
controls.addEventListener('change', render);

// ----------------------- RAYCASTING
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();

var raycastLayer = [];
let hovered = {};
let intersects = [];

window.addEventListener('pointermove', e => {
  // Pointer movement logic
});

window.addEventListener('click', e => {
  // Click event handling logic
});

// Additional code for lighting setup, glyph creation, rendering, and animation

Answer №1

According to your own words, the items are arranged in order of the intersection point distance from the starting point of the ray. Simply select the object located at index zero.

Answer №2

When looking to target a specific object, I utilize a similar method as shown below. To only focus on intersecting a particular group of objects, it is helpful to organize them into layers.

const raycaster = new THREE.Raycaster()
raycaster.layers.set(layer)
raycaster.setFromCamera(screenPosition, this.camera);
const intersectedObjects = raycaster.intersectObjects([mainScene], true);
if (intersectedObjects.length) {
  /* return the targeted object or implement a hover effect */
  return intersectedObjects[0]
} else {
  /* no changes made or remove hover effects from all objects */
  return null
}

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

How to focus on the final element in a JavaScript array

My function is almost there, but I am facing an issue: function prevTrack() { if (playlist_index == (playlist.length - 0)) { playlist_index = -1; } else { playlist_index--; } playlist_status.innerHTML = playlist[playlist_ind ...

Tips for transferring information between various form views in AngularS

I am facing an issue with my multi-step form in AngularJS. I have split the form into different views using ui-router for routing and ngResource for sending data to MongoDB. The problem is that when I submit the form, only the values from the current view ...

Organizing Checkbox Groups for Validation in Bootstrap

My form consists of 2 checkboxes and I only want to submit the form if at least one checkbox is checked. The current code requires both checkboxes to be checked, but I tried grouping them using the name attribute without success. How can I group checkbox ...

NuxtJS Static generated HTML page fails to load JavaScript while accessing /index.html

I'm currently working on a project using Nuxt.js to generate static content, which involves utilizing JavaScript for tasks such as navigation and form functionality. Everything works smoothly when running the page with npm run dev. However, after ex ...

Cannot choose an option using JQuery Select2

Encountering an issue with Select2. The functionality seems to be working fine, except for the inability to select any option. Utilizing select2 version 3.5.3 along with KnockoutJS, CoffeeScript, and JQuery. Here is my select2 code: generateSelect3 =-> ...

Unlock the power of Javascript in Wordpress by converting a string into a dynamic Page Title

Imagine having a custom-coded menu of links that needs to be added to multiple Wordpress pages. The menu is consistent across all pages, except for the variable part of the link text enclosed in square brackets. Here is how the HTML structure looks: <l ...

"Exploring the Effects of Opacity Gradation in

Is there a way to create a face with an opacity gradient in three.js since rgba is not supported and the alpha is not used? I've heard it might be achievable with a ShaderMaterial and custom attributes, but being new to WebGL, I'm still trying t ...

Creating dynamic div elements using jQuery

I used a foreach loop in jQuery to create some divs. Everything seems to be working fine, but for some reason, my divs are missing SOME class properties. Here is the code snippet I am using: $("#item-container").append("<div class=\"panel col-md-2 ...

Encountering a Cross-Origin Resource Sharing (CORS) issue while attempting to load an image from a different

While attempting to use a texture hosted on my own webserver and placing it into the asset-item tag, an error arises. > Access to Image at 'http://192.168.137.1:3000/cat2.jpg' from origin > 'http://localhost' has been blocked by ...

The most efficient method to obtain the accurate value

I'm currently facing an issue with extracting a value from a JSON object. Each JSON object in my array has a name (attribute), a similarity (ignore this for now), and an array named "values" with keys and corresponding values. For each case, I have a ...

Differentiating Typescript will discard attributes that do not adhere to an Interface

Currently, I am working with an API controller that requires a body parameter as shown below: insertUser(@Body() user: IUser) {} The problem I'm facing is that I can submit an object that includes additional properties not specified in the IUser int ...

Steps for incorporating a variable into a hyperlink

I'm trying to achieve something similar to this: var myname = req.session.name; <------- dynamic <a href="/upload?name=" + myname class="btn btn-info btn-md"> However, I am facing issues with making it work. How can I properly ...

What is the best method for storing objects within a Mongoose schema?

Within my node.js project, I am working with three variables: var name = 'Peter'; var surname = 'Bloom'; var addresses = [ {street: 'W Division', city: 'Chicago'}, {street: 'Beekman', city: 'N ...

Is it possible to include pseudo element elements in the configuration of a custom theme in Material UI?

Within my file themeConfig.js, I have defined several theme variables that are utilized to style different components throughout my application. Among these variables, there is a need for implementing the -webkit scrollbar styles for certain components. Du ...

Issue with Gulp and Browserify task: Why is there no output?

I've set up the following task in my gulpfile.js gulp.task('default', ['browserify']) gulp.task('browserify', function () { return browserify('./public/js/x.js') .bundle() .pipe(source('y.js& ...

Utilizing the POST request to signal the server's response of a 404

I'm having trouble sending a POST request to my server in order to update a user's information. Even though I have verified that the URL is correct, I keep receiving a 404 error response. GET requests are working fine, but there seems to be an is ...

Failed attempt to register on localhost through Facebook

I have been attempting to implement the Facebook registration plugin on my localhost, but unfortunately, the registration box is not appearing as expected. Below are some screenshots for reference: Here is the code snippet I have used: <!DOCTYPE html ...

The authentication0 router fails to initiate navigation

I'm currently using Auth0 in combination with Angular 2. The issue I am encountering is that my login code isn't redirecting to the home page after authentication. Based on my understanding, Auth0 does not handle the redirection process itself. ...

Implementing dynamic controls in an ASP.NET MVC5 application using AngularJS

I am currently working on a project that will utilize MVC5, angularJS, and bootstrap for development. One of the key features in my project is a dropdown menu called "expense type". Upon selecting a value from this dropdown, additional controls need to be ...

How do I extract data from the view and utilize it in the controller within an AngularJS application?

I'm currently developing an AngularJS 1.6 app that integrates with the Giphy.com API. One of the key features is displaying an "import date" that comes directly from the API as import_datetime, which is unique to each item. In my attempt to make the ...