Creating a dynamic line in Three.js that connects the closest vertices from two models

I am facing a challenge with loading two models into a scene using OBJloader and the Three.JS library. Some of the models are billboarded by using

model.setRotationFromQuaternion( camera.quaternion );

My main objective is to create lines connecting a vertex on a billboard to a vertex on the corresponding model. These lines should be drawn between the closest points on the two models when the scene is initially loaded. Since the models rotate freely, the lines will need to adjust accordingly as the models rotate, maintaining the connection between the original vertices.

Imagine the billboard as a label and the line as a link between the label and a spot on the rotating model.

How can I accomplish this?

Below is a portion of my code - the issue I am encountering is that all the models have a position of 0,0,0, so I am unsure how to determine the location of a vertex on both the label and the model and then connect them.

 addLabelLines(){
    var geometry = new THREE.Geometry();    

    for ( var i = 0; i < this.labels.length; i ++ ) { 
        var currentLabel = this.labels[i];
        var modelMatchingLabel;
        //find matching model
        for(var j = 0; j < this.models.length; j++){
          if(currentLabel.name.toLowerCase().indexOf(this.models[j].name) >= 0){
            modelMatchingLabel = this.models[j];
          }
        }

        if(!modelMatchingLabel){
          console.warn("no model matching label "+currentLabel.name);
          return;
        }
        else{
          console.log('found model '+modelMatchingLabel.name +" matches label "+currentLabel.name);

          geometry.vertices.push( currentLabel.position );
          geometry.vertices.push( modelMatchingLabel.position );
        }        
    }


    var material = new THREE.LineBasicMaterial( { color: 0x800080 } );

    line = new THREE.Line( geometry, material, THREE.LineSegments );

    scene.add( line );
  }

Answer №1

When searching for the nearest point to draw a line, one must employ the use of "nearest neighbor" algorithms. This example showcases a highly effective method for accomplishing this task.

https://example.com/nearestone

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

Run a Python script to capture mouse coordinates using Selenium

Greetings, I am currently utilizing selenium webdriver to retrieve the X,Y coordinates of the cursor at a specific moment on the webdriver screen. However, I am facing challenges with the implementation of a method that involves using driver.execute_script ...

Having issues with the $addToSet method in my MongoDB API implementation

Despite searching through various topics, I couldn't find a solution to my specific problem. In an effort to enhance my JavaScript skills, I embarked on creating a quote generator. I successfully developed the API and frontend components. However, c ...

Tips for determining the final cost post discount entry

Calculate the final cost with discount Issue with OnChange event function CalculateDiscount() { var quantity = document.getElementById("ticket-count").innerText; var price = document.getElementById("item-price").innerText; var discount = document.getEle ...

Converting a variety of form fields containing dynamic values into floating point numbers

Trying to parse the input fields with a specific class has presented a challenge. Only the value of the first field is being parsed and copied to the other fields. https://i.stack.imgur.com/QE9mP.png <?php foreach($income as $inc): ?> <input ty ...

After resizing, reordering, hiding, or showing columns in the kendo grid, the grid's data source will be set to

I am encountering an issue with my kendo grid where the data disappears after performing certain actions: Reordering columns using mouse drag and drop Resizing columns using mouse drag and drop Hiding columns through the column menu Showing columns throu ...

Using Axios in Vuejs to prompt a file download dialog

I am currently working on figuring out how to trigger a file download dialog box after receiving an Ajax request from the Flask server using Axios. Here is my current client-side code snippet: <script> export default { ... exportCSV: function() { ...

Download CSV file directly in Internet Explorer 10 by choosing to open the file instead of saving it on your device

On my server, I have a link available to download a file: <a id="downloadCSVFile" runat="server" href="javascript:void(0)" onclick="parent.document.location = 'CSVFile.csv';">Download</a> I attempted this method as well: <a id=" ...

Modifying the default error message in Yup: A step-by-step guide

What is the process for modifying the default error message to a custom error message? Specifically, my custom message. const VALIDATION_SCHEME = Yup.object().shape({ numOne: Yup.Number().required('!'), numTwo: Yup.Number() .r ...

Display all months on mobile screen using Mui DesktopDatePicker

Looking for a Better Date Range Picker I've been working on a project that requires a date range picker, and I opted to use the Mui date range picker. While it works well on desktop, I encountered an issue with mobile view where only one month is sho ...

Clicking on a different texture/image allows for the texture to change in Three.js

I am working on creating a 360 image view using Threejs. I have a total of 4 images, with one linked to Threejs and the other 3 displayed as thumbnails at the bottom of the page. When a thumbnail is clicked, the 360 image view should change accordingly. Y ...

The inline $Emit function is not generating the correct random number when using Math.random()

I've been diving into the concept of $emit event in Vue and came across this tutorial: . I tried implementing something similar using Vue2.js, but every time I click the button, it gives me a rounded number instead of a random number like in the guide ...

Issue with Node.js MongoDb query results in the retrieval of all documents instead of the specific

Example of Json Structure: {"address": {"building": "1007", "coord": [-73.856077, 40.848447], "street": "Morris Park Ave", "zipcode": "10462"}, "borough": "Bron ...

Frequently refreshing a page to display the most recent information without needing to reload the entire

I am seeking a solution for updating the comments section on my website live or every 30 seconds. The comments are fetched from a MySQL database using PHP: <?php $link = mysql_connect('localhost', 'root', ''); ...

having trouble with npm installation of firebase-tools

I am encountering an issue while attempting to set up firebase-tools for my android studio project. Here is the error message that I am facing: Microsoft Windows [Version 10.0.15063] (c) 2017 Microsoft Corporation. All rights reserved. C:\WINDOWS&bs ...

The variable process.env.CLIENT_ID is functioning correctly within a function, but does not work when declared as a global

Trying to implement oAuth for Google API Using .env file to hide sensitive variables with .gitignore Facing an issue when trying to define the CLIENT_ID variable globally CLIENT_ID = process.env.CLIENT_ID When I run and log the variable outside of a fun ...

Switching the visibility of rows in a table

Imagine this as my example table: <table> <tr> <td>a</td> <td>one</td> <td>two</td> </tr> <tr> <td>b</td> <td>three</td> <td>four</t ...

Encountered a error 500 while attempting to POST using Postman in Node.js

After successfully setting up the server, I encountered an issue when attempting to create a user using Postman with the details in Application/JSON format. The server responded with: POST /sign-up 500. Initially, I tried specifying utf-8 without succes ...

Prevent draggable function in jQuery-UI for specific elements

I'm in the process of creating a website that mimics a desktop interface, and I want to be able to easily move around the windows. To achieve this functionality, I am incorporating jQuery-UI along with the .draggable() method. My current HTML structur ...

How to Retrieve the Absolute Index of the Parent Column Using jQuery Datatables

I recently developed a custom column filtering plugin for datatables, but I've encountered a minor issue. Within each column footer, I have added text inputs, and now I am trying to capture their indexes on keyup event to use them for filtering. In ...

"Experience the latest version of DreamFactory - 2.0.4

I'm encountering a 404 error when I send a request to my new DSP. GET http://example.com/api/v2/sericename/_table/tablename 404 (Not Found) Upon checking the Apache error.log, I found this message: ... Got error: PHP message: REST Exception #404 &g ...