Utilizing raycasting to target specific components within a glTF model and incorporate event listeners

I'm in the process of creating an interactive web application. Recently, I successfully imported a glb file into my scene. Now, I'm looking to incorporate two key functionalities:

  1. onMouseover: When hovering over one of the elements within the object, I aim to change the color of that specific element.
  2. The 3D object comprises a Texture_Group[Object3D], detailed in the console log below. The Texture_Group is essentially a collection of 3D letters(objects) spelling out "HAJDUK". However, these letters are imported as a grouped .glb file. I intend to implement an event listener so that clicking on each individual letter(object) will load a different link corresponding to that particular object.

I'm a bit confused about whether I can achieve this using only a raycaster or if I need to delve deeper into traversing the Texture_Group and creating a conditional logic structure for this purpose. If anyone has insights on how to go about this, particularly with the raycaster and scene traversal, I would greatly appreciate the guidance. This is my first time posing a question, so if additional information is required, please do let me know.

I've utilized some online code to traverse my scene in the console.log and customized it to suit my project needs.

Here is an excerpt from my app.js code:

/*jshint esversion: 6 */
let scene, camera, renderer, h, controls, raycaster, mouse;

function init() {
  // Initialization of various components including camera, renderer, lights, controls, and loader
}

init();

//Render Loop
render();

function render() {
  // Request animation frame logic
}

//windowResize
function windowResize() {
  //Adjust camera aspect ratio and renderer size
}

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

//Console log traverse for scene objects
function dumpVec3(v3, precision = 3) {
  // Function to format vector objects
}

function dumpObject(obj, lines = [], isLast = true, prefix = '') {
  // Recursive function for logging information about scene objects
}

console.log:

Excerpt from the console.log detailing object hierarchy and properties

Answer №1

After discussing in the comments, it has been determined that all functionalities can be easily implemented using a Raycaster.

If you want to detect when the mouse hovers over a group of objects in the scene, you can group them together using THREE.Group or THREE.Object3D containing child meshes.

You can then attach a mousemove event to a function that updates a global variable mouse with the current mouse position in the viewport.

function onMouseMove(event) {
  event.preventDefault();
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
}

Within your animation loop, you can perform a raycast based on the current mouse position and check for intersections with objects in the group. Here, you can handle updating the color of the objects when they intersect with the ray.

function raycast() {
  raycaster.setFromCamera(mouse, camera);
  var intersects = raycaster.intersectObjects(group.children);
  // Rest of the code for handling intersections
}

Additionally, you can attach a click event to trigger a function when an object is clicked while intersecting with the ray.

function onMouseClick(event) {
  if (INTERSECTED !== null) {
    clickFunction(INTERSECTED);
  }
}

You can see these functionalities in action in this JSFiddle example.

Feel free to reach out if you need further clarification.


If the objects within your TEXTURE_GROUP are not organized neatly into meshes, it's recommended to pack each letter into a single mesh. Then, when iterating through them, you can add them to an Object3D or Group if they are not already grouped together.

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

Caution: It is important that every child within an array or iterator is assigned a distinct "key" property

As a new developer in ReactJS, I have created a table using ReactJS on the FrontEnd, NodeJS on the BackEnd, and MySQL for the database. My goal is to retrieve data with a Select request on the table. For my frontend: class ListeClients extends Component ...

When running npm install -g, the package is being installed into a global directory on

For a considerable amount of time, I have been working with node and npm. Now, as I embark on a more extensive project using these tools, I've encountered an issue. Whenever I execute 'sudo npm install -g', the installation is directed to &a ...

Error occurred when trying to run 'npm run dev' on vite: Unable to access the file "node_modules/react/jsx-dev-runtime.js"

After successfully creating a Vite app, I encountered three errors when trying to run the app with npm run dev: [ERROR] Cannot read file "node_modules/react/jsx-dev-runtime.js": Access is denied. [ERROR] Cannot read file "node_modules/react/index.js": Acc ...

Encountering difficulty selecting a dropdown sub-menu using Selenium WebDriver

I'm currently working on automating a website with selenium webdriver. The issue I'm encountering is that when I try to click on a menu item, the submenu pops up (actually a misplaced dropdown, UI issue), and although I can locate the element of ...

Transform a date string into a date entity

Collecting the user's input for the date and saving it as a string variable. The format of the value is Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time) My goal is to convert this string back into a new Date() object in order to make additiona ...

Unravel intricate JSON data and display it in a Material-UI table

How to convert the complex JSON data provided below into a material-ui table similar to the example shown. Each row may contain either a single value or multiple rows in a single box. I have attempted to display the data in 2 columns only, but need help wi ...

Retrieve information dynamically from a JSON file using the get JSON function and iterate through the data

I possess a JSON file that I wish to utilize in creating dynamic HTML elements with the JSON content. Below is the provided JSON data: { "india": [ { "position": "left", "imgurl":"3.jpg" }, { ...

How do I adjust the controls in Three.js to align with the previous camera position?

The three.js scene is equipped with W,A,S,D and left and right arrow controls, which allow for movement of the camera. However, the controls restrict the camera's movement to a fixed direction in the scene, rather than relative to its previous positio ...

Tips for excluding specific elements when clicking on a document

JavaScript $(document).click( function () { alert("Hello there"); } Web Development <div id="wrapper"> <div id="inner-1"> <div id="sub-inner1">Sub Inner1 Content</div> <div id="sub-inner2">Sub Inner2 Content&l ...

Set the value obtained from a resolved promise to a mutable reference object in a React component

I am in the process of developing a random movie generator. I am utilizing an external API to retrieve a list of movies and then selecting one randomly from the returned data. The current implementation is as follows: export default function Page() { con ...

AngularJS $http.post() response function not executing in the correct sequence

When calling a function from my angular controller to make a $http.post() request, the code below the function call is executing before the successFunction(), preventing the code inside the if block from running. How can I ensure the if block executes wi ...

The element is inferred to have the 'any' type. No index signature matching the parameter type 'string' was found on the 'User1' type

I have been experimenting with computed properties in TypeScript, but I've encountered a specific issue: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User1'. ...

`Datatables sorting feature for British date and time`

I'm currently attempting to organize a column in a table using the DataTables plugin that contains UK date and time formats such as: 21/09/2013 11:15 Implementing Ronan Guilloux's code: jQuery.extend( jQuery.fn.dataTableExt.oSort, { "uk_dat ...

I am currently transferring cross-site forgery tokens through jQuery strings. However, on the subsequent page, I create a fresh token which means their original tokens will no longer align

Alright, so I've been storing the tokens in a session: Session::get('token', 'randomtokenstringhere'); Every time a form is submitted, whether successfully or not, I generate a new token and update their session token. But let&ap ...

Obtain a custom token after next authentication through Google login

Utilizing next js, next auth, and a custom backend (flask), I have set up an API Endpoint secured with jwt token. In my next js frontend, I aim to retrieve this jwt token using the useSession hook to send requests to these API Endpoints. Everything functio ...

ElementUI Cascader not rendering properly

Utilizing elementUI's cascading selector to present data, I have crafted this code in accordance with the official documentation. <el-cascader v-model="address" :options="addressOptions" :props="{expandTrigger: 'hover'}" ...

Encountering a 404 XHR Error when attempting to add a component in Angular 4.1.0 within Plunker

Having some trouble setting up Angular 4 on Plunker and adding a new component. The following URL is where I'm working: https://plnkr.co/edit/1umcXTeug2o6eiZ89rLl?p=preview I've just created a new component named mycomponent.ts with the necessar ...

Highlighting the current menu item by comparing the URL and ID

Looking to make my navigation menu items active based on URL and ID, rather than href. None of the suggested solutions (like this one, this one, or this one) have worked for me. This is how my Navigation is designed: <nav id="PageNavigation"& ...

Troubaling with AngularJS Routing issues

I am encountering an issue with my routing system. The "otherwise" case is functioning correctly, however, when I click on a menu item, the routing does not load the corresponding page automatically. Can someone assist me in identifying what is wrong with ...

An issue occurred while attempting to read words from JSON file

My current issue involves loading words from JSON into my webpage. The images are functioning properly, thankfully. I have already successfully loaded the necessary images through JSON onto my webpage. However, I am still in need of loading words through ...