In order to trigger the mousedown event in Three.js, I have found that I need to click and gently move my cursor

There seems to be an issue with the code below, as the "intersects" variable does not populate with items in the onDocumentMouseDown event handler when I simply click an object. It only detects the object clicked when I click and slightly drag the mouse before it recognizes the item. I am also using trackballcontrols, which may be a factor in this behavior. You can view an example of this in the following jsfiddle link: http://jsfiddle.net/marktreece/xvQ3f/

When you click on the cube in the jsfiddle example, you'll notice that the color does not change as expected. However, if you click on the cube and then move it slightly before releasing the mouse button, the color does change. How can I modify the code so that a simple click on the object is enough to trigger the desired action?

Below is the code for my mousedown event handler:

function onDocumentMouseDown( event ) {
    event.preventDefault();
    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( scene.children, true );
    if ( intersects.length > 0 ) {
        intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
    }
}

Answer №1

After reviewing your code, it seems that the issue lies in the fact that the raycasting is functioning correctly and the intersection variable is not empty. The problem arises from the use of TrackballControls, where the rendering only occurs when there is a change in the camera's position. This explains why even a slight mouse movement results in a color change in the box.

To address this issue, I have modified your animate function to include an additional call to the render function. While this solution resolves the problem, it's worth noting that it may not be the most efficient approach since rendering is now being performed every frame.

function animate() {
    try{
        requestAnimationFrame( animate );
        controls.update();
        render();
    }
    catch(err){
        alert("animate error. " + err.message);
    }
}

I hope this clarification proves helpful to you!

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

Check if a rotated rectangle lies within the circular boundary of the canvas

I have a rectangular shape that has been rotated using the ctx.rotate method, and there is also an arc on the canvas. My goal is to determine if any part of the rectangle lies within the boundaries of the arc. See the example below: https://i.sstatic.net/ ...

Searching for a MongoDB document using its unique identifier

Currently, I am working with Node.js and MongoDB where my database is hosted on MongoHQ (now compose.io). I have come to understand that document IDs are converted to hex strings, but I am struggling to retrieve a document using its ID. In my dataset, the ...

What could be causing the network error that keeps occurring when attempting to sign in with Google using React and Firebase?

Having an issue with Google authentication using Firebase. I set up the project on Firebase console and copied the configuration over to my project. Enabled Google sign-in method in the console which was working fine initially. But, after 2 days when I tri ...

What is the best way to format 100K to appear as 100,000?

function formatNumberWithCommas(num) { return num >= 1000 ? `${Number.parseFloat((num).toFixed(3))}` : num; } ...

Transform a JSON array with keys and values into a structured tabular format in JSON

Looking to transform the JSON data below for a Chart into a format suitable for an HTML table: var chartJson = [ { header : '2016', values : [1, 5, 9] }, { header : '2017', values : [2, 4, 8] ...

The image slider is blocking the dropdown functionality of the navbar on mobile devices

My code is experiencing a conflict of events. I have created a menu bar using nav bar, as well as an image slider called the caroussel. The issue arises when the window is minimized - the menu bar fails to drop down properly with the presence of the caro ...

How to trigger a JavaScript function using a button click

I've been struggling to figure out why my JavaScript code isn't functioning properly within Ionic. Can anyone guide me on how to store a number in a variable, display that variable, and increment it when a button is clicked? I have successfully ...

What indicators should we look for to decide if JavaScriptExecutor is needed in a Selenium C# project?

Encountering an exception with TestInChrome1 - "OpenQA.Selenium.ElementNotInteractableException: element not interactable". On the other hand, using JavaScriptExecutor in TestInChrome2 resolves the issue. Some key questions arise: What is causing the ...

Iterating over an object and inserting values into a JavaScript object using the ascending count as the identifier

Illustration: { Are you a coffee drinker?: yes, Do you like to exercise regularly?: no, How often do you eat out at restaurants?: 3 times a week, What is your favorite type of cuisine?: Italian } Results: {yes: 1, no: 1, 3 time ...

Tips for setting up a full-size image with nextJS and the <Image /> component

Upgrading NextJS to the latest version has resulted in some errors when using the Image component: // import Image from 'next/image' <div style={Object.assign({}, styles.slide, style)} key={key}> <Image src={src} alt="&quo ...

What is preventing ng-click from assigning a variable with the value from ng-repeat in AngularJS?

I'm currently working on a feature for an app that allows users to select font styles from Google Fonts for specific text elements. Here's the code snippet I have so far: <ul ng-init='headerFont="mono"'> <li ng-repeat=&apos ...

Mastering the use of useMasterKey in Parse with Node.js: A guide

Greetings everyone, I have developed my app using parse.com but now I need to utilize the master key as some users have administrative roles. Initially, I attempted to use the JS SDK but was advised to switch to Cloud Code. So, I tried using Express and ...

The tooltip in nvd3 is displaying the index instead of the label

I'm encountering an NVD3 tooltip issue with my multichart (multiline chart). The XAxis labels are set as JAN, FEB, MAR... DEC. However, when I hover over the graph, it displays 0, 1, 2, 3... 11 as the tooltip title instead of the month names. Here is ...

What is the process for appending a value to an array of JSON objects?

I have a JSON array containing objects which I need to pass the values to the DataTables. [{ _id: '58a2b5941a9dfe3537aad540', Country: 'India', State: 'Andhra Pradesh', District: 'Guntur', Division: ...

Ensure menu options are aligned to the right using material-ui

My material-ui menu currently has the following setup: <span> <Link to="/issues"> <Button style={isActive(history, "/issues")}>Issues </Button> </Link> <Link to="/users"> <Button style={isActive(his ...

Maintain the same javascript variable throughout multiple pages

I am working on a project that involves utilizing a database along with 2 drop down menus. Through the use of JavaScript, I am able to capture the value selected from the drop down menus and then pass it on to my PHP script. The PHP script retrieves releva ...

NodeJS package 'jquery' npm not functioning properly (issue with $.on())

I've successfully installed and loaded jquery by using $ = require('jquery'); However, when I attempt to utilize it: app.get('/', function (req, res) { res.render('index'); $.on('ready', function () { ...

The textbox is only enabled when a specific selection is made in the dropdown menu

My JavaScript code seems to be malfunctioning: <script language="javascript" type="text/javascript"> function ShowExpenseReport(Expense_Report_ID) { var width = screen.width; var leftpad = (width - 740) / 2; var jsopti ...

The functionality of ngModel is not functioning properly on a modal page within Ionic version 6

Currently I am working on an Ionic/Angular application and I have encountered a situation where I am attempting to utilize ngModel. Essentially, I am trying to implement the following functionality within my app: <ion-list> <ion-item> <ion ...

Issues with simple jquery and javascript: unable to add the class ".has-error" and onclick event not properly defined

Currently, I am working with jQuery version 2.1.4 and JavaScript to implement a straightforward form validation using Bootstrap. During this process, I have encountered three peculiar issues. While I am confident that my jQuery code is properly functi ...