Developing a unique offset for a polyline in ThreeJS

I am working with a Geometry that has vertices forming a polyline. However, the offset I have created is not accurate. Currently, I am calculating the center of the geometry and then offsetting a value relative to this center. This method is resulting in an incorrect offset.

This is my current code:

    var size = 10;
    var geo = this.mesh.geometry,
        center = new THREE.Vector3();

    geo.computeBoundingBox();
    geo.boundingBox.getCenter(center);

    geo.vertices.forEach(function(vertice){
        var C = new THREE.Vector3()
        C.subVectors( vertice, center ).multiplyScalar( 1 + ( size / C.length() ) ).add( center );
        vertice.copy(C);
    });

    geo.verticesNeedUpdate = true;

After analyzing this issue, I am considering a different approach which involves using the previous and next vertices to calculate a more precise base point for the offset. The diagram below illustrates what I aim to achieve. While I know the vertices a, b, and c, I am uncertain about how to determine the vertex at the intersection of the two lines at a 90-degree angle.

By adopting this new method, I hope to calculate a more accurate offset per vertex with improved distance options. Can anyone provide insights on how to calculate the purple dot between points a and b?

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

Answer №1

From my understanding of the situation, it seems that you can determine the position of the "purple vertex" (center) using the code provided below. Keep in mind that while vertices A, B, and C are directly obtained, you might need to make some adjustments depending on how the vertices are stored:

  var size = 10;
  var geo = this.mesh.geometry,
      center = new THREE.Vector3();

  geo.computeBoundingBox();
  geo.boundingBox.getCenter(center);

  // Obtain vertices A, B, and C which the purple vertex will project towards
  var A = geo.vertices[0]
  var B = geo.vertices[1]
  var C = geo.vertices[2]

  // Calculate vectors between A, B, and C for determining the purple vertex position.
  const dirAB = new THREE.Vector3().subVectors(B, A).normalize()
  const vecAC = new THREE.Vector3().subVectors(C, A)

  // Determine the distance along AB where the purple vertex lies
  const proj = dirAB.dot(vecAC)

  // Compute the position of the center (purple vertex) based on the distance 'proj' along the unit vector dirAB
  center = new THREE.Vector3()
    .copy(A)
    .addScaledVector(dirAB, proj)

  // Uncomment the following block if needed to update vertices based on calculated positions
  // geo.vertices.forEach(function(vertice){
  //     var C = new THREE.Vector3()
  //     C.subVectors( vertice, center )
  //     .multiplyScalar( 1 + ( size / C.length() ) ).add( center );
  //     vertice.copy(C);
  // });

  geo.verticesNeedUpdate = true;

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

Ways to navigate through a webpage without encountering any overflow issues

My window is too small to scroll, but I still need the ability to do so. Is it possible to scroll even when the height of the container is not large enough to display the scrollbar? Below is the code I am using to achieve scrolling: setTimeout(function() ...

Issue with displaying custom in-line buttons in JQGrid

Currently, I am utilizing jqgrid 3.8.2 (I am aware it's not the latest version, but I plan on updating it soon after seeking some advice :-)) I have successfully incorporated a couple of in-line buttons into my jqgrid using the default formatter &apo ...

Issues encountered while attempting to verify password confirmation within a React form using Joi

I have been struggling to implement a schema for validating a 'confirm password' form field. While researching how to use Joi for validation, I noticed that many people recommend using the Joi.any() function. However, every time I attempt to use ...

Attempting to console.log data from within useEffect, but unfortunately no information is being logged

function FetchUserAccounts() { const [userAccounts, setUserAccounts] = useState(); useEffect(() => { async function fetchUserAccountsData() { const response = await fetch( 'https://proton.api.atomicassets.io/atomicassets/v1/a ...

The best way to consistently execute setTimeout in order, regardless of the timing, is by utilizing a Promise

I have the following code snippet: var timeOne = new Promise(function(resolve,reject) { setTimeout(function(){ console.log('This is one'); }, Math.random() * 1000); }); var timeTwo = new Promise(function(resolve,reject) { s ...

The Creation of the 3D Globe Featuring the World's Wonders: Explore the Entire Planet

After reading an informative article on creating a 3D globe (Making of the World Wonders 3D Globe), I successfully replaced the demo markers with my own markers. Now, I am interested in rendering the entire earth in the window, not just the top 30%: Check ...

How can I retrieve the state from another component in React?

I am facing a challenge in reactjs where I need to dynamically disable a button based on a value retrieved from another component. In my primary component (main.js), the Button needs to be disabled or enabled based on a specific value obtained from a sepa ...

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

Version 66 of Three.Js brings exciting new features, including the addition

As of the latest version v66 of Three.js, it seems that the Gizmo transform controls are no longer functioning properly. To see a demo, click on the link below: Here is the basic code snippet: let geometry = new THREE.CubeGeometry( 200, 200, 200 ); let m ...

How do I view a wildcard in my ID selector using jQuery?

When I want to initially hide various content scattered around the page, I usually use the following jQuery code: $('#objective_details, #time_estimate_details, #team_members_details, #resources_details').hide(); Is there a method to utilize a ...

A method to efficiently send multiple axios GET requests by incrementing the URL parameters

Is there a way to efficiently send multiple HTTP GET requests using Axios? For instance: let maxRequests = 3000; let currentRequest = 0; do { currentRequest = currentRequest + 1; await response = axios.get(`https://example.com/${currentRequest}` ...

Chrome is throwing a syntax error with an unexpected token in jQuery replaceWith

jQuery('div#top').replaceWith('<div id="top"> </div>') When I try to replace the entire content of the top div using jQuery, Chrome gives me an error: "Uncaught SyntaxError: Unexpected token" on the first line. I'm no ...

Using more than one button to activate a single Material-UI Popper component

I recently found myself in a situation where I needed to activate the Material-UI <Popper /> component from various clickable elements. According to the Popper component API on the official Material-UI website, setting the anchorEl property determine ...

Trigger the opening of a bootstrap modal from an external source on the current page

One common question is how to load a modal from another page onto the current page, or how to open a modal on the current page when it loads. My idea is a little different: I want to click on an image hotspot (like a person in a team photo) on the /home p ...

How can I implement a feature in React.js where clicking a button triggers a Canvas to draw something?

I am trying to implement a <button> component that will trigger a specific function to draw on my HTML5 Canvas element. This is how the project files are structured and how I have passed the necessary props -> The main drawing function is locate ...

The document inside the database is displayed in italicized text when it is stored in Firebase

try { // establish a new collection named 'pactLists' const pactListsCollection = collection(db, "pactLists"); // used for storing records of created pacts by users. // generate a unique id for the pact and set it as the invite c ...

Regular expression for parsing any CSS font properties

Does anyone have a reliable regex to break down a css font string into its individual components? 12px arial italic bold sans-serif 12px/50px verdana etc ...

Having trouble retrieving POST data with the Webextensions API

Looking to retrieve POST data using a Webextensions API on page load. Implemented a background script with the code below: browser.webRequest.onBeforeSendHeaders.addListener( getPostData, { urls: ['<all_urls>'], types: ["main_fr ...

React js: Changing Material-UI functional code to class component results in TypeError

After utilizing the material ui login page code, I discovered that it is a functional component. To meet my specific requirements, I decided to convert it into a class component. However, during the conversion process, an error was encountered: "Cannot ass ...

Interactive state for associated product within list without order

I am currently working on a project that involves an unordered list with separate list items. The menu design includes product images in the top list item and the corresponding product names in the list item below. I have successfully implemented a hover s ...