"Enhancing User Experience with JavaScript Double Click Feature in Three.js

Currently, I have implemented a double click function that allows the user to double click on a car model, displaying which objects have been intersected such as wipers, grille, and tires. These intersections are listed along with the number of items the double click has intersected with.

Now, I am attempting to enhance this functionality so that when a specific part of the car, like the tires, is clicked on, a paragraph with relevant information about the tires is displayed. I understand that this involves checking the name of the intersecting object and displaying the corresponding text if it intersects, but every time I attempt to make modifications, the existing function breaks, rendering it non-functional.

While I am not an expert in JavaScript or Three.js, I am finding it challenging to advance the functionality of this function.

Any suggestions on how to achieve this? I have included the complete double click function below, with the focus on the part where it checks for intersections near the bottom, that requires alterations.

// On Mouse double click event function
function onDoubleClick(event) {
// Set the mouse down flag to false
mouseDown = false;

// Canvas x (left) and y (top) position
var canvasLeft = 0;
var canvasTop = 0;

// "event.clientX" is the mouse x position. "event.clientY" is the mouse y position
var tempX = event.clientX - canvasLeft;
var tempY = event.clientY - canvasTop;
// Create a normalised vector in 2d space
var vector = new THREE.Vector3((tempX / window.innerWidth) * 2 - 1, - (tempY / innerHeight) * 2 + 1, 0.5);

// Unproject a 2D point into the 3D word
// Use the camera projection matrix to transform the vector to the 3D world space
vector.unproject(camera);

// Send a ray in the direction the user has clicked from the cameras position
var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());

// Check if the ray has intersected with any objects and get intersections
var intersects = raycaster.intersectObjects(objects, true);

// Check if intersected with objects
if (intersects.length > 0) {
    var tempStr = "Number of items: " + intersects.length + " ";
    // List the items that were hit
    for(var i=0; i < intersects.length; i++){
        if(intersects[i].object.name != ""){
            // The mesh name set above
            tempStr += " | Name: " + intersects[i].object.name;
        } else {
            // The names inside the model
            tempStr += " | Name: " + intersects[i].object.parent.name;
        }
    }

    //Debug information
    document.getElementById("debugInfo").innerHTML = tempStr + ".<br>";
    //END
}

}

EDIT: This is the entire code for the javascript file, as altering elements of the double click function seems to stop the page from loading.

Answer №1

Greetings Macast,

I kindly urge you to ensure that the following lines are not missing from your code:

var objets = [];
var raycaster = new THREE.Raycaster();

Additionally, for each component of the car, please include this line:

objects.push( mesh );

For example:

var geometry = new THREE.RingGeometry( 1, 5, 32 );
var material = new THREE.MeshBasicMaterial( { color: 0xff0000, side: THREE.DoubleSide } );
var simpleTire = new THREE.Mesh( geometry, material );
simpleTire.name = 'tire';
objects.push( simpleTire );
scene.add( simpleTire );

Afterward, it's a straightforward process:

if ( intersects.length > 0 ) {
    switch(intersects[0].object.name){
        case 'tire':
            console.log('A beautiful red tire');
        break;
        case 'motor':
            console.log('An innovative electric motor');
        break;
        }
}

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

Leveraging clusters in Node.js for REST API deployment

Within my node.js application, I have a REST API that contains complex logic with extensive looping, taking over 7 seconds to complete. As the loop count may increase in the future, the processing time is bound to increase as well. To optimize performance ...

Using Vue.js to dynamically change attribute values based on a condition

I am currently displaying a v-tippy in the following manner: <label v-tippy content="My content text"> Everything is functioning as expected, but now I want to display it based on a condition show_tip == true. Is there a way to achieve th ...

"Can you provide guidance on binding data in vue.js when there is a dash (-) in the key of the JSON

My JSON data is structured as follows: { "color-1": "#8888", "color-2": "#000" } I am attempting to bind this variable with a style tag for a Vue component. However, my current approach seems to not be functioning as expected. <div v-bind:sty ...

I'm encountering an issue in my node application where it is unable to access the push

I am a beginner in the world of node.js and express. Whenever I try to start my application using the command npm start, I encounter an error message saying Cannot Read property push of undefined from my index.js file. The problematic code snippet looks l ...

Combine multiple sets of data frames together into one cohesive list using an appropriate function in R

Is there a way to efficiently convert multiple data frames into a list using an R function? Let's say I have the following 3 dataframes: A <- data.frame(m = c(121, 122, 121, 122, 125, 126), r = c(0.1, 0.2, 0.3, 0.4, 0.1, 0.2),q1 = c(124, 126, 12 ...

Using Spring MVC and Thymeleaf to dynamically load new HTML pages on ajax calls

Hello there, I'm looking to dive into using thymeleaf for my web application. My goal is to create a simple website with HTML pages. Below is the URL of my landing page controller that returns the index.html page: @RequestMapping("/index") public Str ...

The form validation in Bootstrap 5 seems to be having some trouble triggering

Here is the form setup for allowing users to change their account password: <div class="signup-form-small"> <form method="post" name="frmPassword" id="frmPasswo ...

interrupt the node script using async behavior

I encountered an issue while running the npm install command to install a list of modules on Node, specifically related to async. TypeError: undefined is not a function What could be causing this problem? var fs = require( "fs" ), path = require( ...

Is it possible to utilize X-Y coordinates as repositories for values beyond just X-Y coordinates themselves?

I am in the process of creating a tile-based grid and I need to expand the X-Y coordinates to include additional values for determining characteristics of each tile, such as resources (for example, food, water, stone, lumber) within a game context. Conside ...

Tips for utilizing the Apollo cache consistently during page transitions in NextJs

In the official examples repository of NextJS, I found this apolloClient.js file: import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client' import { concatPagination } from '@apollo/client/utilities' import merge from &apos ...

Using a comma format while typing in Angular ensures that the input field

When using jqxwidget from here, the default format includes commas separated by underscores. I am looking to have the field empty initially, with commas appearing as the user types - similar to a F2 cell renderer. For example, typing 100 should display a ...

Differences between Javascript object constructor and object literal

Similar Questions: Creating Objects - New Object or Object Literal Notation? Literal Notation VS. Constructor to Create Objects in JavaScript As I embark on my initial Javascript tutorial journey, I have come across two distinct methods of creatin ...

Navigating the website with curtain.js and anchor tags

Currently, I am working on a website located at www.TheOneCraft.co.uk. I have incorporated the curtain.js jQuery plugin to create animated slide/pages as users scroll down. However, I have been unsuccessful in making the navigation bar follow this animati ...

What is an alternative method to retrieve POST fields in Express without relying on the bodyParser middleware?

Recent updates to Express have suggested to stop using the bodyParser middleware, as indicated by a debug message. Upon further research, it appears that bodyParser is simply a wrapper to the json and urlencoded middlewares. In its place, the latest versio ...

What is the best way to send {...rest} properties to a text field in react material?

When using a material textfield inside a wrapper component and passing the remaining props as {...otherprops} in a JavaScript file, everything works fine. However, when attempting to do the same in TypeScript, an error occurs. const TextFieldWrapper = (pro ...

Jquery animation in Wordpress without any need for scrolling

My Wordpress site features some animations that work flawlessly when the site is scrolled. The code looks like this: jQuery(document).ready(function($){ $(window).scroll( function(){ if(!isMobile) { $('.animate_1').each ...

How to toggle the visibility of an element in an array using AngularJS and JavaScript

Is there a way to show additional information when an item in ng-repeat is clicked, and then hide this extra info when the mouse leaves that same item? One issue I am facing with the code snippet below is that when a user clicks on a different item, it al ...

ui-grid row size set to automatically adjust using rowHeight : 'auto'

Has anyone else experienced this strange behavior with ui-grid? When I set the rowHeight to auto, each cell in the same row ends up with different heights. One of the cells contains multiline data, which seems to be causing issues for ui-grid. I've ev ...

Animating Text Changes with JavaScript and jQuery

In my HTML, I have an input type="text" element and I want to attach an event handler that triggers when the text is changed. The issue arises because this input's value is dynamically updated by another JavaScript function, causing the event handler ...

Command to conceal components for users visiting as guests

I'm looking to develop a directive that hides specific elements for guest users. Here is the current code I have: angular.module('someMod') .directive('premiumUser', premiumUser) .controller('PremiumUserCtrl', Pr ...