What is the best way to determine the nearest vertex to a given 3D point?

https://i.sstatic.net/Ooh8W.png

Objective:

I am aiming to identify the closest vertex to the clicked point.

Components Needed:

  • Perspective camera
  • Icosahedron geometry (applied basicmeshmaterial with wireframe)
  • Rotating geometry
  • Raycaster

Current Click Handler Code:

mouse = new THREE.Vector2();
mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
mouse.y = - (event.clientY / renderer.domElement.clientHeight) * 2 + 1;

raycaster.setFromCamera(mouse, camera);

const intersects = raycaster.intersectObject(icosahedron);

// Closest 3D point: intersects[0].point
// Corresponding object face: intersects[0].face

Appreciate your help!

Answer №1

Here are three simple steps to follow:

  • Start by converting the vertex positions of the intersecting face from local to global coordinates
  • Next, calculate the distance to a given 3D point
  • Finally, arrange the distances in ascending order

-

vertices = [
  intersects[0].face.a,
  intersects[0].face.b,
  intersects[0].face.c
];

vertices.forEach( function(vId,i){
  vertices[i] = mesh.geometry.vertices[vId].clone();
  vertices[i].l2w = mesh.localToWorld(vertices[i].clone());
  vertices[i].id = vId;
  vertices[i].index = i;
  vertices[i].distance = vertices[i].l2w.distanceTo(intersects[0].point);
})

vertices.sort( function(a,b){
  return a.distance - b.distance;
})

Check out this JSFiddle link for more details

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

displaying a grey box on Google Maps using an *ngIf directive

I am working on a component that displays a map. @Component({ selector: "panda-map", template: ` <div class="map" [style.height.px]="height"> </div> ` }) export class PandaMapComponent implements OnInit { @Input ...

Utilizing AJAX requests to execute create, update, and delete actions all from one streamlined file instead of separating them into three distinct

In my JavaScript code, I am currently making XMLHttpRequests to separate PHP files for different functionalities in my app - like add.php, update.php, and delete.php. However, having three separate files feels repetitive. Is there a way to consolidate al ...

Utilize MongoDB and Mongoose to efficiently delete data using the findByIdAndRemove() method and redirect users accordingly

Currently, I am facing an issue with the DELETE method as the res.redirect doesn't seem to be working. The code in question involves trying to remove a record from MongoDB using findByIdAndRemove(): app.delete("/car", (req, res) => { Car.fi ...

Having difficulty fully modifying the jQuery class

My goal is to create an emoji system using a file named emoji.css to store the emojis. The names of the emojis are stored in a JavaScript array with some modifications. When users input an emoji text like :emoji: or :another-emoji:, JavaScript should check ...

Unable to concatenate values from Object in JavaScript

Although it may seem trivial, the following code is giving me trouble: window.temp1.targetInterests It gives me back: Object {Famosos: "Famosos", Musica: "Música", Humor: "Humor"} I attempted to join it: window.temp1.targetInterests.join('/&apos ...

How can I prevent my service worker from caching text/html documents such as the index page?

When my PWA is offline, I want it to display the offline.html page. However, even when the homepage fails to fetch due to being offline, my service worker still uses cached text/html requests to retrieve the homepage. To create my PWA, I am utilizing work ...

How to access an array mapped to a specific key within an object in JavaScript

Is there a way to access an array mapped to a specific key in a JavaScript object? data = {}; data.key = 'example'; data.value = 'test'; data.list = [111, 222, 333]; Viewing the list of items works fine: alert(data.list); // displays ...

Converting Dates in Javascript to the Format YYYYMMDDHHMMSS

Can you guide me on the process of transforming the date format Mon Apr 16 2018 19:00:00 GMT-0500 (Central Daylight Time) into 20180416190000 (YYYYMMDDHHMMSS)? ...

Exploring Substrings in jQuery/JavaScript

Issue Can anyone help me with locating a specific set of words within a string (gval in this scenario) that defines the specific wordset? if (gval.indexOf("define") > -1){ console.log("Hey! gval has Define"); } var gval = input.val().trim().toLowe ...

md- The datePicker component consistently encounters errors with Date instances

I encountered an issue where the error message The ng-model for md-datepicker must be a Date instance. Currently the model is a: string appeared. I am utilizing moment.js library to handle dates. Within the view section: <md-datepicker ng-model="Model ...

Refine the search outcomes by specifying a group criteria

I have a scenario where I need to filter out service users from the search list if they are already part of a group in another table. There are two tables that come into play - 'group-user' which contains groupId and serviceUserId, and 'gro ...

undefined event typescript this reactjs

I have come across the following TypeScript-written component. The type definitions are from definitelytyped.org. I have bound the onWheel event to a function, but every time it is triggered, this becomes undefined. So, how can I access the referenced el ...

Executing a Javascript GET request leading to a 301 redirect

Struggling to identify the issue at hand, I have turned to this platform in hopes of finding a solution. The setup involves an angularJS app with a GoLang/Gorilla mux server backend. The web app runs on http://localhost:8888/, while the server operates at ...

Disabling the ripple effect on the primary action in React Material lists: A Step-by-Step

I was attempting to include two action buttons at the opposite ends of a list component. https://i.stack.imgur.com/juv8F.gif When clicking on the secondary action (delete icon on the right), the ripple effect is confined to just the icon. On the othe ...

Adding points to vertices on mesh geometry based on their distance

My scene includes a THREE.Geometry with more than 5,000 vertices. I am looking to add THREE.Points to the scene for only 3 specific vertices of the mesh within the geometry. My goal is to achieve a similar outcome as shown in this example: https://i.sstat ...

Exploring the attributes of ExtJS display objects

I am looking for a way to efficiently display JSON content from a servlet in a browser using a list format. While I could use the definition list tag in pure HTML, I need to load everything dynamically without manually parsing and creating the HTML code. ...

Utilizing the invoke() method within the each() function in Cypress to access the href attribute

I recently started using Cypress and I'm attempting to retrieve the href attribute for each div tag within a group by utilizing invoke(), however, it is resulting in an error. Could anyone provide guidance on the correct way to achieve this? cy.get(&a ...

Why is JSON ParseError still returned by jQuery .ajax call despite JSON being seemingly correct?

Despite having valid JSON on jsonlint.com, I'm encountering a ParseError. Below is the jQuery code snippet: $.ajax({ url: path, type: 'GET', data: {}, cache: false, dataType: 'json', contentType: 'app ...

Utilize Vue.js 3 and InertiaJs to Retrieve Session Information in Laravel 9

I am currently working on my initial Laravel project, incorporating Vuejs for the frontend. One of the key features of my application is allowing a Super admin to log in as a User (impersonate). By clicking on the Impersonate Button, the word impersonate g ...

What's preventing me from drawing a line on this D3.js chart with my Angular code?

I am attempting to create a graph on my webpage using the D3.js library for JavaScript. I am able to draw a line on an SVG using HTML, but when I try to draw a line using JavaScript, I encounter the error message: ReferenceError: d3 is not defined. Even t ...