Is there a way to retrieve the specific point that was clicked on within a THREE.Points object?

I'm currently experimenting with a raycaster to identify points on a 2D plane of points...

function dynamic(x) { x.dynamic = true; return x; }
geometry.addAttribute("position", dynamic(new THREE.BufferAttribute(positions, 3)));
geometry.addAttribute("color", dynamic(new THREE.BufferAttribute(colors, 3)));
var grid = new THREE.Points(geometry, material);
scene.add(grid);

function mouseDownHandler(event) {
    if (event.button == 0) {
        event.preventDefault();
        var mouse = new THREE.Vector2();
        var box = canvas.getBoundingClientRect();
        mouse.x = ((event.clientX - box.left) / (box.right - box.left)) * 2.0 - 1.0;
        mouse.y = ((event.clientY - box.bottom) / (box.top - box.bottom)) * 2.0 - 1.0;
        raycaster.setFromCamera(mouse, camera);
        var intersects = raycaster.intersectObject(grid);
        if (intersects.length > 0) {
// Why does my intersect not work?
// I _believe_ I'm calculating the mouse positions correctly.
// But, the intersects are always way off. (Or, I'm misinterpreting
// something...)
            console.log("mouse: ", mouse);
            console.log("First Intersect:", intersects[0]);
            console.log("First Point:", intersects[0].point);
        }
    }
}

You can access the complete code here: for the webpage, and for the actual code..

The issue lies within the mouseDownHandler function. Essentially, when you click your mouse, I want it to indicate which point was actually clicked. However, when I click near the bottom left of the grid, the mouse coordinates approximate to {-1,-1}(which I believe is expected, right?) and they approximate to {1,1} near the top right.

How do I determine the index of the point that was clicked? I've attempted clicking on all four corner points, expecting at least one of them to be 0 considering how I constructed the data (using just 2 nested for loops). Yet, none of them are close to 0, and the points in intersects[0].point always appear significantly distant. Where am I making a mistake?

Thank you!

Answer №1

For those who come across this in the future, I discovered that the issue was not with the mouse calculation, but rather with the minimum distance set for the perspective camera.

camera = new THREE.PerspectiveCamera(fov, 1, 1e-16, 1000);

The minimum distance of 1e-16 was too small for the perspective camera to function properly. Once I adjusted it to

camera = new THREE.PerspectiveCamera(fov, 1, 1e-2, 1000);

everything worked as expected. Looking back, it's clear that an underflow error was likely occurring. (You can see the working version here: and the failing version with just that one change here: (Both tested with the original mouseDownHandler))

Answer №2

Your mouse coordinates are important:

var box = canvas.getBoundingClientRect();
var mouseX = event.clientX - box.left;
var mouseY = event.clientY - box.top;

var mousePos = new THREE.Vector2 (
        2 * (mouseX / canvas.width) - 1,
    1 - 2 * (mouseY / canvas.height));

For further details, you can visit:

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 can you personalize a website script by deactivating it using uBlock Origin and then reintegrating it as a userscript?

Can you imagine if it were possible to address a problematic portion of a script on a website by preventing the original script from loading, copying the source code, editing it, and then re-injecting it as a userscript with Tampermonkey? I attempted this ...

Utilizing Angular to automatically extract keys from nested objects in a response

In my Angular application, I am facing a challenge with accessing nested responses from the server. The data structure contains multiple responses within one parent object, and I am struggling to dig deeper into it. Here is the code snippet I have so far: ...

Retrieving input value in an Android WebView

I recently attempted to extract the value of an input type and store it as a string within my Android WebView. Unfortunately, I couldn't find a straightforward solution. The snippet of code in my HTML file is as follows: <input class="input100 ...

The absence of reactivity is evident when working with composition-api and nuxt3

I've got a Nuxt code snippet that is functioning correctly: <template lang="pug"> div {{ isActive }} !-- Reactivity is working fine, isActive switches from false to true --! </template> <script> export default { data() ...

Issue with Backbone collection not being updated despite making a JSONP request

Recently, I delved into the world of Backbone.js and currently, I am immersed in developing an app using Brunch that makes a JSONP request to an external API for populating my collection and models. Despite following guidance from previous posts (here and ...

The ng-cloak feature in Angular JS seems to be malfunctioning as it is displaying the expression symbol when the

As someone who is new to AngularJS, I am faced with a challenge of dealing with html code that displays before it gets evaluated. It's quite frustrating to see the expressions appear first and then the actual values. I tried using ng-cloak in the body ...

What is the best way to retrieve data from a jQuery AJAX call when it returns?

function isNewUsername(str){ var result; $.post('/api/isnewusername', {username:str}, function(data) { result = data.result; }, "json"); return result; } I am encounte ...

Execute the Angular filter again when there is a change in the scope

I am currently working on an application where Users have the ability to switch between kilometers and miles for unit distances. To handle this, I created a custom filter that converts the distances accordingly: app.filter('distance', function() ...

The "require" keyword cannot be used in a Node-RED Function node

When working with a Node-RED Function Node, the first line I include is: var moment = require('moment-timezone'); I'm attempting to create a timezone accurate date/time stamp for sensor data. However, when this node runs, I encounter the fo ...

"Unlocking the Potential: Maximizing the Benefits of the top.gg Vote Web

My bot has been verified on top.gg, and I'm looking to offer rewards to users who vote for my bot. How can I detect when someone votes for my bot, get their ID, check if it's the weekend, and take action after the vote? Essentially, how do I util ...

Is the input field not properly centered on the page?

Can someone explain why the input field is not aligning in the center? I am new to web development and need some assistance. <input type="text" id="search_bar" class="form-control" placeholder="Search" align="center"> In my CSS, I've ...

detecting user interactions with hyperlinks

Can links be intercepted in an Angular application to block specific URLs like YouTube links without adding custom attributes or elements? Is it possible to intercept all clicks on links within the scope of a particular controller's view without modi ...

Using VeeValidate with v-menu

Has anyone been able to successfully apply veevalidate to vuetify's v-menu component? I've tried using the validation-provider container with other HTML inputs and it works fine, but when I try to integrate it with v-menu, it doesn't seem t ...

The Ajax script is failing to retrieve search results

I am encountering an issue with my normal AJAX search functionality in which I need to retrieve data from a database when the form is submitted. The problem arises when trying to filter data between two specific dates using separate pages, it works fine bu ...

Issue with modal component triggering unexpected page reload

I'm encountering a strange issue with my modal in Vue.js. It only appears on a specific page named 'Item', but when I click on a different view, the page reloads unexpectedly. This problem seems to occur only with the route containing the mo ...

What is the best way to link JavaScript files from a Grails plugin in a separate Grails application?

I have developed a unique plugin that offers multiple Grails controllers and domain objects. Additionally, I have created several AngularJS UI components that I wish to utilize in various other projects. These specific files are located within the web-app ...

The concept of dynamic schema in Mongoose allows for flexibility and

Currently, I am working on creating a product schema that involves setting pricing in different currencies. However, I am facing confusion regarding how to dynamically create currency options. The pricing may vary in one currency or multiple currencies as ...

A problem encountered in specific JavaScript code

As a newcomer to JavaScript, I have encountered an issue while trying to run this script: <html> <head> <title>Exploring javascript functionalities</title> </head> <body> <p id="demo">I ...

The POST request to the localhost API endpoint resulted in a 404 Not Found error

Whenever I try to send a POST request to "/api/auth/signup" in my JavaScript application, I keep getting a 404 Not Found error. My goal is to create a MERN application for a Modern Real Estate Marketplace. This is the code snippet causing the is ...

Issue with Bootstrap jQuery dynamic table edit/delete/view button functionality not functioning as expected

Could really use some assistance with this issue. I have a DataTable that includes a button in the last column which offers options like Edit/Delete/View. When clicked, it should delete the entire row. However, I'm struggling to access the current ele ...