Using three.js to create a hover effect that highlights the edges of a cube with LineSegmentsGeometry

I am currently utilizing LineSegmentsGeometry and LineMaterial to render thick cube edges. My objective is to dynamically change the color of the edge when it is hovered over.

const edgesGeometry = new LineSegmentsGeometry().fromEdgesGeometry(
  new THREE.EdgesGeometry(mesh.geometry, 40)
);
const colors = [];
for (let i = 0; i < edgesGeometry.attributes.position.count; i++) {
  colors.push(0, 0, 0);
}
edgesGeometry.setAttribute(
  "color",
  new THREE.Float32BufferAttribute(colors, 3)
);
const edgesMaterial = new LineMaterial({
  color: "black",
  vertexColors: true,
  linewidth: 0.001
});
const line = new THREE.LineSegments(edgesGeometry, edgesMaterial);
const setLineColor = (color) => {
  const { index, object } = intersected;
  object.geometry.attributes.color.setXYZ(index, color.r, color.g, color.b);
  object.geometry.attributes.color.setXYZ(index + 1, color.r, color.g, color.b);
  object.geometry.attributes.color.needsUpdate = true;
};

Currently, this code is only functional with thin lines using LineBasicMaterial. Is there a way to achieve this effect with bold lines? I also need to apply this logic to other shapes as well. sandbox here https://codesandbox

Answer №1

If you want to achieve this, go for bold lines! LineSegmentsGeometry (bold lines) has a different structure compared to EdgesGeometry, so you need to adjust your approach accordingly.

Upon reviewing your example, here are some key points to consider:

  1. When working with bold lines, instanced BufferAttributes are generated for the start and end points of each line (instanceStart and instanceEnd). To determine the correct number of colors for a segment, do not rely on geometry.attributes.position. Instead, use attributes.instanceStart.count and utilize the LineSegmentsGeometry.setColors function to set up the appropriate instanced color attributes for each segment.

  2. Make sure the LineMaterial color is white so that the vertex colors are visible when combined.

  3. When dealing with bold lines, use "faceIndex" instead of "index" when intersecting. Use this information to update the color fields on the instanceColorStart and instanceColorEnd attributes accordingly.

Check out this modified demo based on your code, with some brief inline comments for guidance:

https://jsfiddle.net/juoz5yLv/1/

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

Tips for concealing an alert using an 'if' statement

There is an alert that pops up on a website only on specific days of the year. My query is: How can I make the alert hidden if the date is not one of those special days? I attempted the code below, but it seems to just delay the alert based on certain con ...

Executing an HTTP POST request without properly encoding a specific parameter

I am attempting to communicate with an unauthorized third-party API using Node and the request module. Below is the code that generates the request: request.post( { url: url, headers: MY_HEADERS_HERE, followAllR ...

How can Node.js developers properly utilize PM2 for their projects?

I'm currently contemplating a switch from forever to PM2 as a way to ensure my node application stays up and running. I find myself puzzled by the various recommended methods for initiating a process: $ pm2 start app.js -i 4 # Daemonize pm2 and Star ...

Identifying an Object by Clicking with the Mouse in three.js

After successfully loading 3 external models into my scene using the json loader, I am now trying to retrieve the name of the clicked model/object. Below is the code snippet that I used to load the models: var object_material = new THREE.MeshBasicMateria ...

What does {``} denote in react-native programming?

During my participation in a collaborative project, I noticed that there is a significant amount of {' '} being used. For instance: <Text> {' '} {constant.Messages.PointText.hey} {this._user.first_name || this._user ...

Exploring nested JSON objects in Angular and rendering them in PHP

On my Json page, I have data organized like this : [{ "qid": "1", "contester": "0", "answer": "0", "question": "What would you do after getting into ...

Using jQuery to adjust the length of a string to fit within a specific width

I am working with a table and need to input strings in each cell, but they are wider than the cell width. I want to shorten the strings without breaking lines, and add '...' at the end to show that the string is long. The table consists of aroun ...

Encountered a TypeError in Angular printjs: Object(...) function not recognized

I'm currently working on integrating the printJS library into an Angular project to print an image in PNG format. To begin, I added the following import statement: import { printJS } from "print-js/dist/print.min.js"; Next, I implemented the pri ...

JsPlumb: Incorrect endpoint drawn if the source `div` is a child of a `div` with `position:absolute`

My current setup involves two blue div elements connected by jsPlumb. You can view the setup here: https://jsfiddle.net/b6phv6dk/1/ The source div is nested within a third black div that is positioned 100px from the top using position: absolute;. It appe ...

Tips for showcasing a restricted amount of data with Angular.js

I've been exploring different ways to limit the results using limitTo, but unfortunately, I'm encountering unexpected issues. Currently, the entire list is being displayed when I only want to show 8 key-value items in a 4/4 block format. You can ...

Struggling with handling numbers and special symbols in the Letter Changes problem on Coderbyte

Hello I have been struggling to find a solution for my current issue. The problem lies within an exercise that requires changing only alphabetical characters, but test cases also include numbers and special characters which are being altered unintentionall ...

Difficulty switching back and forth between three varying heights

I have a container with a button labeled "Show more". Upon clicking the button, the height of the container will transition through 3 different states. <div class="segment-suggestion-content height-small"> <div class="segment-suggestion-sh ...

jQuery Each Loop failing to retrieve data during iteration

Encountered a peculiar issue while working with an each loop. The situation may seem a bit tangled but I'm constrained to manipulating the code with jQuery due to it being part of a larger framework that can't be modified. As a way to simplify t ...

I'm encountering a problem with handling errors in Express.js: A critical error has occurred while attempting to execute the _runMicro

Currently, I am utilizing the Blizzard API Battle.Net to fetch information regarding a character's name and the realm they inhabit. In certain cases, a user may request a character that does not exist, prompting Blizzard to return a 404 error response ...

The policy of the Authorization Server mandates the use of PKCE for this particular request

I'm currently utilizing the authentication service provided by Hazelbase through next-auth. However, during deployment, an error message pops up stating Authorization Server policy requires PKCE to be used for this request. Please take note that Haze ...

Update the innerHTML content dynamically every 5 seconds with Vue.js

I'm working on a new website and I'd like to spice things up by changing the header text with a random word every 5 seconds. Here's the starting point: const header = document.querySelector('.header') const needs = ['jacket& ...

Ways to avoid Next.js from creating a singleton class/object multiple times

I developed a unique analytics tool that looks like this: class Analytics { data: Record<string, IData>; constructor() { this.data = {}; } setPaths(identifier: string) { if (!this.data[identifier]) this.da ...

What is the process to designate a specific value to a key in an array?

I need assistance in updating the description array within the schema by adding the about and link values, followed by using the .save() function to store it in the database. Any guidance on this issue would be greatly appreciated. Thank you for your help. ...

Guide on navigating to a different page following a successful Google Sign In within React18

I'm facing an issue with redirection after signing in with Google on my React 18 project. Despite successfully logging in, the page does not redirect as expected. Below is a snippet of my Login.jsx file where the Google login functionality is implemen ...

The value of document.readyState remains as 'complete' even while the page is still actively loading on the frontend

Below is the code I implemented to verify if the page has finished loading: JavascriptExecutor js = (JavascriptExecutor)Driver; pageLoadStatus = js.executeScript("return document.readyState").toString(); Despite still visibly loading, the document.readyS ...